View.Layout.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  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. // A layout was performed so a draw is needed
  367. // NeedsLayout may still be true if a dependent View still needs layout after SubViewsLaidOut event
  368. SetNeedsDraw ();
  369. return true;
  370. }
  371. return false;
  372. }
  373. /// <summary>
  374. /// Performs layout of the view and its subviews using the content size of either the <see cref="SuperView"/> or
  375. /// <see cref="Application.Screen"/>.
  376. /// </summary>
  377. /// <remarks>
  378. /// <para>
  379. /// See the View Layout Deep Dive for more information:
  380. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  381. /// </para>
  382. /// <para>
  383. /// This method is intended to be called by the layout engine to
  384. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  385. /// </para>
  386. /// </remarks>
  387. /// <returns><see langword="false"/>If the view could not be laid out (typically because dependency was not ready). </returns>
  388. public bool Layout () { return Layout (GetContainerSize ()); }
  389. /// <summary>
  390. /// Sets the position and size of this view, relative to the SuperView's ContentSize (nominally the same as
  391. /// <c>this.SuperView.GetContentSize ()</c>) based on the values of <see cref="X"/>, <see cref="Y"/>,
  392. /// <see cref="Width"/>,
  393. /// and <see cref="Height"/>.
  394. /// </summary>
  395. /// <remarks>
  396. /// <para>
  397. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  398. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  399. /// are left unchanged.
  400. /// </para>
  401. /// <para>
  402. /// This method does not arrange subviews or adornments. It is intended to be called by the layout engine to
  403. /// prepare the view for layout and is exposed as a public API primarily for testing purposes.
  404. /// </para>
  405. /// <para>
  406. /// Some subviews may have SetRelativeLayout called on them as a side effect, particularly in DimAuto scenarios.
  407. /// </para>
  408. /// </remarks>
  409. /// <param name="superviewContentSize">
  410. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.GetContentSize ()</c>).
  411. /// </param>
  412. /// <returns><see langword="true"/> if successful. <see langword="false"/> means a dependent View still needs layout.</returns>
  413. public bool SetRelativeLayout (Size superviewContentSize)
  414. {
  415. Debug.Assert (_x is { });
  416. Debug.Assert (_y is { });
  417. Debug.Assert (_width is { });
  418. Debug.Assert (_height is { });
  419. CheckDimAuto ();
  420. // TODO: Should move to View.LayoutSubViews?
  421. SetTextFormatterSize ();
  422. int newX, newW, newY, newH;
  423. try
  424. {
  425. // Calculate the new X, Y, Width, and Height
  426. // If the Width or Height is Dim.Auto, calculate the Width or Height first. Otherwise, calculate the X or Y first.
  427. if (_width.Has<DimAuto> (out _))
  428. {
  429. newW = _width.Calculate (0, superviewContentSize.Width, this, Dimension.Width);
  430. newX = _x.Calculate (superviewContentSize.Width, newW, this, Dimension.Width);
  431. if (newW != Frame.Width)
  432. {
  433. // Pos.Calculate gave us a new position. We need to redo dimension
  434. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  435. }
  436. }
  437. else
  438. {
  439. newX = _x.Calculate (superviewContentSize.Width, _width, this, Dimension.Width);
  440. newW = _width.Calculate (newX, superviewContentSize.Width, this, Dimension.Width);
  441. }
  442. if (_height.Has<DimAuto> (out _))
  443. {
  444. newH = _height.Calculate (0, superviewContentSize.Height, this, Dimension.Height);
  445. newY = _y.Calculate (superviewContentSize.Height, newH, this, Dimension.Height);
  446. if (newH != Frame.Height)
  447. {
  448. // Pos.Calculate gave us a new position. We need to redo dimension
  449. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  450. }
  451. }
  452. else
  453. {
  454. newY = _y.Calculate (superviewContentSize.Height, _height, this, Dimension.Height);
  455. newH = _height.Calculate (newY, superviewContentSize.Height, this, Dimension.Height);
  456. }
  457. }
  458. catch (LayoutException)
  459. {
  460. //Debug.WriteLine ($"A Dim/PosFunc function threw (typically this is because a dependent View was not laid out)\n{le}.");
  461. return false;
  462. }
  463. Rectangle newFrame = new (newX, newY, newW, newH);
  464. if (Frame != newFrame)
  465. {
  466. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height
  467. // This will set _frame, call SetsNeedsLayout, and raise OnViewportChanged/ViewportChanged
  468. SetFrame (newFrame);
  469. if (_x is PosAbsolute)
  470. {
  471. _x = Frame.X;
  472. }
  473. if (_y is PosAbsolute)
  474. {
  475. _y = Frame.Y;
  476. }
  477. if (_width is DimAbsolute)
  478. {
  479. _width = Frame.Width;
  480. }
  481. if (_height is DimAbsolute)
  482. {
  483. _height = Frame.Height;
  484. }
  485. if (!string.IsNullOrEmpty (Title))
  486. {
  487. SetTitleTextFormatterSize ();
  488. }
  489. if (SuperView is { })
  490. {
  491. SuperView?.SetNeedsDraw ();
  492. }
  493. else if (Application.TopLevels.Count == 1)
  494. {
  495. // If this is the only TopLevel, we need to redraw the screen
  496. Application.ClearScreenNextIteration = true;
  497. }
  498. }
  499. if (TextFormatter.ConstrainToWidth is null)
  500. {
  501. TextFormatter.ConstrainToWidth = GetContentSize ().Width;
  502. }
  503. if (TextFormatter.ConstrainToHeight is null)
  504. {
  505. TextFormatter.ConstrainToHeight = GetContentSize ().Height;
  506. }
  507. return true;
  508. }
  509. /// <summary>
  510. /// INTERNAL API - Causes the view's subviews and adornments to be laid out within the view's content areas. Assumes
  511. /// the view's relative layout has been set via <see cref="SetRelativeLayout"/>.
  512. /// </summary>
  513. /// <remarks>
  514. /// <para>
  515. /// See the View Layout Deep Dive for more information:
  516. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/layout.html"/>
  517. /// </para>
  518. /// <para>
  519. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  520. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  521. /// </para>
  522. /// <para>Raises the <see cref="SubViewsLaidOut"/> event before it returns.</para>
  523. /// </remarks>
  524. internal void LayoutSubViews ()
  525. {
  526. if (!NeedsLayout)
  527. {
  528. return;
  529. }
  530. CheckDimAuto ();
  531. Size contentSize = GetContentSize ();
  532. OnSubViewLayout (new (contentSize));
  533. SubViewLayout?.Invoke (this, new (contentSize));
  534. // The Adornments already have their Frame's set by SetRelativeLayout so we call LayoutSubViews vs. Layout here.
  535. if (Margin is { SubViews.Count: > 0 })
  536. {
  537. Margin.LayoutSubViews ();
  538. }
  539. if (Border is { SubViews.Count: > 0 })
  540. {
  541. Border.LayoutSubViews ();
  542. }
  543. if (Padding is { SubViews.Count: > 0 })
  544. {
  545. Padding.LayoutSubViews ();
  546. }
  547. // Sort out the dependencies of the X, Y, Width, Height properties
  548. HashSet<View> nodes = new ();
  549. HashSet<(View, View)> edges = new ();
  550. CollectAll (this, ref nodes, ref edges);
  551. List<View> ordered = TopologicalSort (SuperView!, nodes, edges);
  552. List<View> redo = new ();
  553. foreach (View v in ordered.Snapshot ())
  554. {
  555. if (!v.Layout (contentSize))
  556. {
  557. redo.Add (v);
  558. }
  559. }
  560. var layoutStillNeeded = false;
  561. if (redo.Count > 0)
  562. {
  563. foreach (View v in ordered)
  564. {
  565. if (!v.Layout (contentSize))
  566. {
  567. layoutStillNeeded = true;
  568. }
  569. }
  570. }
  571. // If the 'to' is rooted to 'from' it's a special-case.
  572. // Use Layout with the ContentSize of the 'from'.
  573. // See the Nested_SubViews_Ref_Topmost_SuperView unit test
  574. if (edges.Count > 0 && GetTopSuperView () is { })
  575. {
  576. foreach ((View from, View to) in edges)
  577. {
  578. // QUESTION: Do we test this with adornments well enough?
  579. to.Layout (from.GetContentSize ());
  580. }
  581. }
  582. NeedsLayout = layoutStillNeeded;
  583. OnSubViewsLaidOut (new (contentSize));
  584. SubViewsLaidOut?.Invoke (this, new (contentSize));
  585. }
  586. /// <summary>
  587. /// Called from <see cref="LayoutSubViews"/> before any subviews
  588. /// have been laid out.
  589. /// </summary>
  590. /// <remarks>
  591. /// Override to perform tasks when the layout is changing.
  592. /// </remarks>
  593. protected virtual void OnSubViewLayout (LayoutEventArgs args) { }
  594. /// <summary>
  595. /// Raised by <see cref="LayoutSubViews"/> before any subviews
  596. /// have been laid out.
  597. /// </summary>
  598. /// <remarks>
  599. /// Subscribe to this event to perform tasks when the layout is changing.
  600. /// </remarks>
  601. public event EventHandler<LayoutEventArgs>? SubViewLayout;
  602. /// <summary>
  603. /// Called from <see cref="LayoutSubViews"/> after all sub-views
  604. /// have been laid out.
  605. /// </summary>
  606. /// <remarks>
  607. /// Override to perform tasks after the <see cref="View"/> has been resized or the layout has
  608. /// otherwise changed.
  609. /// </remarks>
  610. protected virtual void OnSubViewsLaidOut (LayoutEventArgs args) { Debug.Assert (!NeedsLayout); }
  611. /// <summary>Raised after all sub-views have been laid out.</summary>
  612. /// <remarks>
  613. /// Subscribe to this event to perform tasks after the <see cref="View"/> has been resized or the layout has
  614. /// otherwise changed.
  615. /// </remarks>
  616. public event EventHandler<LayoutEventArgs>? SubViewsLaidOut;
  617. #endregion Core Layout API
  618. #region NeedsLayout
  619. // We expose no setter for this to ensure that the ONLY place it's changed is in SetNeedsLayout
  620. /// <summary>
  621. /// Indicates the View's Frame or the layout of the View's subviews (including Adornments) have
  622. /// changed since the last time the View was laid out.
  623. /// </summary>
  624. /// <remarks>
  625. /// <para>
  626. /// Used to prevent <see cref="Layout()"/> from needlessly computing
  627. /// layout.
  628. /// </para>
  629. /// </remarks>
  630. /// <value>
  631. /// <see langword="true"/> if layout is needed.
  632. /// </value>
  633. public bool NeedsLayout { get; private set; } = true;
  634. /// <summary>
  635. /// Sets <see cref="NeedsLayout"/> to return <see langword="true"/>, indicating this View and all of it's subviews
  636. /// (including adornments) need to be laid out in the next Application iteration.
  637. /// </summary>
  638. /// <remarks>
  639. /// <para>
  640. /// The <see cref="MainLoop"/> will cause <see cref="Layout()"/> to be called on the next
  641. /// <see cref="Application.Iteration"/> so there is normally no reason to call see <see cref="Layout()"/>.
  642. /// </para>
  643. /// </remarks>
  644. public void SetNeedsLayout ()
  645. {
  646. NeedsLayout = true;
  647. if (Margin is { SubViews.Count: > 0 })
  648. {
  649. Margin.SetNeedsLayout ();
  650. }
  651. if (Border is { SubViews.Count: > 0 })
  652. {
  653. Border.SetNeedsLayout ();
  654. }
  655. if (Padding is { SubViews.Count: > 0 })
  656. {
  657. Padding.SetNeedsLayout ();
  658. }
  659. // TODO: Optimize this - see Setting_Thickness_Causes_Adornment_SubView_Layout
  660. // Use a stack to avoid recursion
  661. Stack<View> stack = new (InternalSubViews.Snapshot ().ToList ());
  662. while (stack.Count > 0)
  663. {
  664. Debug.Assert (stack.Peek () is { });
  665. View current = stack.Pop ();
  666. if (!current.NeedsLayout)
  667. {
  668. current.NeedsLayout = true;
  669. if (current.Margin is { SubViews.Count: > 0 })
  670. {
  671. current.Margin.SetNeedsLayout ();
  672. }
  673. if (current.Border is { SubViews.Count: > 0 })
  674. {
  675. current.Border.SetNeedsLayout ();
  676. }
  677. if (current.Padding is { SubViews.Count: > 0 })
  678. {
  679. current.Padding.SetNeedsLayout ();
  680. }
  681. foreach (View subview in current.SubViews)
  682. {
  683. stack.Push (subview);
  684. }
  685. }
  686. }
  687. TextFormatter.NeedsFormat = true;
  688. if (SuperView is { NeedsLayout: false })
  689. {
  690. SuperView?.SetNeedsLayout ();
  691. }
  692. if (this is not Adornment adornment)
  693. {
  694. return;
  695. }
  696. if (adornment.Parent is { NeedsLayout: false })
  697. {
  698. adornment.Parent?.SetNeedsLayout ();
  699. }
  700. }
  701. #endregion NeedsLayout
  702. #region Topological Sort
  703. /// <summary>
  704. /// INTERNAL API - Collects all views and their dependencies from a given starting view for layout purposes. Used by
  705. /// <see cref="TopologicalSort"/> to create an ordered list of views to layout.
  706. /// </summary>
  707. /// <param name="from">The starting view from which to collect dependencies.</param>
  708. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  709. /// <param name="nEdges">
  710. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  711. /// indicating a dependency.
  712. /// </param>
  713. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  714. {
  715. foreach (View? v in from.InternalSubViews)
  716. {
  717. nNodes.Add (v);
  718. CollectPos (v.X, v, ref nNodes, ref nEdges);
  719. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  720. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  721. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  722. }
  723. }
  724. /// <summary>
  725. /// INTERNAL API - Collects dimension (where Width or Height is `DimView`) dependencies for a given view.
  726. /// </summary>
  727. /// <param name="dim">The dimension (width or height) to collect dependencies for.</param>
  728. /// <param name="from">The view for which to collect dimension dependencies.</param>
  729. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  730. /// <param name="nEdges">
  731. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  732. /// indicating a dependency.
  733. /// </param>
  734. internal void CollectDim (Dim? dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  735. {
  736. if (dim!.Has (out DimView dv))
  737. {
  738. if (dv.Target != this)
  739. {
  740. nEdges.Add ((dv.Target!, from));
  741. }
  742. }
  743. if (dim!.Has (out DimCombine dc))
  744. {
  745. CollectDim (dc.Left, from, ref nNodes, ref nEdges);
  746. CollectDim (dc.Right, from, ref nNodes, ref nEdges);
  747. }
  748. }
  749. /// <summary>
  750. /// INTERNAL API - Collects position (where X or Y is `PosView`) dependencies for a given view.
  751. /// </summary>
  752. /// <param name="pos">The position (X or Y) to collect dependencies for.</param>
  753. /// <param name="from">The view for which to collect position dependencies.</param>
  754. /// <param name="nNodes">A reference to a set of views representing nodes in the layout graph.</param>
  755. /// <param name="nEdges">
  756. /// A reference to a set of tuples representing edges in the layout graph, where each tuple consists of a pair of views
  757. /// indicating a dependency.
  758. /// </param>
  759. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  760. {
  761. // TODO: Use Pos.Has<T> instead.
  762. switch (pos)
  763. {
  764. case PosView pv:
  765. Debug.Assert (pv.Target is { });
  766. if (pv.Target != this)
  767. {
  768. nEdges.Add ((pv.Target!, from));
  769. }
  770. return;
  771. case PosCombine pc:
  772. CollectPos (pc.Left, from, ref nNodes, ref nEdges);
  773. CollectPos (pc.Right, from, ref nNodes, ref nEdges);
  774. break;
  775. }
  776. }
  777. // https://en.wikipedia.org/wiki/Topological_sorting
  778. internal static List<View> TopologicalSort (
  779. View superView,
  780. IEnumerable<View> nodes,
  781. ICollection<(View From, View To)> edges
  782. )
  783. {
  784. List<View> result = new ();
  785. // Set of all nodes with no incoming edges
  786. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  787. while (noEdgeNodes.Any ())
  788. {
  789. // remove a node n from S
  790. View n = noEdgeNodes.First ();
  791. noEdgeNodes.Remove (n);
  792. // add n to tail of L
  793. if (n != superView)
  794. {
  795. result.Add (n);
  796. }
  797. // for each node m with an edge e from n to m do
  798. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  799. {
  800. View m = e.To;
  801. // remove edge e from the graph
  802. edges.Remove (e);
  803. // if m has no other incoming edges then
  804. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  805. {
  806. // insert m into S
  807. noEdgeNodes.Add (m);
  808. }
  809. }
  810. }
  811. if (!edges.Any ())
  812. {
  813. return result;
  814. }
  815. foreach ((View from, View to) in edges)
  816. {
  817. if (from == to)
  818. {
  819. // if not yet added to the result, add it and remove from edge
  820. if (result.Find (v => v == from) is null)
  821. {
  822. result.Add (from);
  823. }
  824. edges.Remove ((from, to));
  825. }
  826. else if (from.SuperView == to.SuperView)
  827. {
  828. // if 'from' is not yet added to the result, add it
  829. if (result.Find (v => v == from) is null)
  830. {
  831. result.Add (from);
  832. }
  833. // if 'to' is not yet added to the result, add it
  834. if (result.Find (v => v == to) is null)
  835. {
  836. result.Add (to);
  837. }
  838. // remove from edge
  839. edges.Remove ((from, to));
  840. }
  841. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  842. {
  843. if (ReferenceEquals (from.SuperView, to))
  844. {
  845. throw new LayoutException (
  846. $"ComputedLayout for \"{superView}\": \"{to}\" "
  847. + $"references a SubView (\"{from}\")."
  848. );
  849. }
  850. throw new LayoutException (
  851. $"ComputedLayout for \"{superView}\": \"{from}\" "
  852. + $"linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  853. );
  854. }
  855. }
  856. // return L (a topologically sorted order)
  857. return result;
  858. } // TopologicalSort
  859. #endregion Topological Sort
  860. #region Utilities
  861. /// <summary>
  862. /// INTERNAL API - Gets the size of the SuperView's content (nominally the same as
  863. /// the SuperView's <see cref="GetContentSize ()"/>) or the screen size if there's no SuperView.
  864. /// </summary>
  865. /// <returns></returns>
  866. private Size GetContainerSize ()
  867. {
  868. // TODO: Get rid of refs to Top
  869. Size superViewContentSize = SuperView?.GetContentSize ()
  870. ?? (Application.Top is { } && Application.Top != this && Application.Top.IsInitialized
  871. ? Application.Top.GetContentSize ()
  872. : Application.Screen.Size);
  873. return superViewContentSize;
  874. }
  875. // BUGBUG: This method interferes with Dialog/MessageBox default min/max size.
  876. // TODO: Get rid of MenuBar coupling as part of https://github.com/gui-cs/Terminal.Gui/issues/2975
  877. // TODO: Refactor / rewrite this - It's a mess
  878. /// <summary>
  879. /// Gets a new location of the <see cref="View"/> that is within the Viewport of the <paramref name="viewToMove"/>'s
  880. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  881. /// </summary>
  882. /// <remarks>
  883. /// If <paramref name="viewToMove"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  884. /// <see cref="Application.Top"/> the position will be bound by <see cref="Application.Screen"/>.
  885. /// </remarks>
  886. /// <param name="viewToMove">The View that is to be moved.</param>
  887. /// <param name="targetX">The target x location.</param>
  888. /// <param name="targetY">The target y location.</param>
  889. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  890. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  891. /// <returns>
  892. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  893. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubViews is called on the correct View.
  894. /// </returns>
  895. internal static View? GetLocationEnsuringFullVisibility (
  896. View viewToMove,
  897. int targetX,
  898. int targetY,
  899. out int nx,
  900. out int ny
  901. )
  902. {
  903. int maxDimension;
  904. View? superView;
  905. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  906. {
  907. maxDimension = Application.Screen.Width;
  908. superView = Application.Top;
  909. }
  910. else
  911. {
  912. // Use the SuperView's Viewport, not Frame
  913. maxDimension = viewToMove!.SuperView.Viewport.Width;
  914. superView = viewToMove.SuperView;
  915. }
  916. if (superView?.Margin is { } && superView == viewToMove!.SuperView)
  917. {
  918. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  919. }
  920. if (viewToMove!.Frame.Width <= maxDimension)
  921. {
  922. nx = Math.Max (targetX, 0);
  923. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  924. //if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  925. //{
  926. // nx = Math.Max (viewToMove.Frame.Right, 0);
  927. //}
  928. }
  929. else
  930. {
  931. nx = 0; //targetX;
  932. }
  933. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  934. var menuVisible = false;
  935. var statusVisible = false;
  936. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  937. {
  938. menuVisible = Application.Top?.MenuBar?.Visible == true;
  939. }
  940. else
  941. {
  942. View? t = viewToMove!.SuperView;
  943. while (t is { } and not Toplevel)
  944. {
  945. t = t.SuperView;
  946. }
  947. if (t is Toplevel topLevel)
  948. {
  949. menuVisible = topLevel.MenuBar?.Visible == true;
  950. }
  951. }
  952. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  953. {
  954. maxDimension = menuVisible ? 1 : 0;
  955. }
  956. else
  957. {
  958. maxDimension = 0;
  959. }
  960. ny = Math.Max (targetY, maxDimension);
  961. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  962. {
  963. maxDimension = statusVisible ? Application.Screen.Height - 1 : Application.Screen.Height;
  964. }
  965. else
  966. {
  967. maxDimension = statusVisible ? viewToMove!.SuperView.Viewport.Height - 1 : viewToMove!.SuperView.Viewport.Height;
  968. }
  969. if (superView?.Margin is { } && superView == viewToMove?.SuperView)
  970. {
  971. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  972. }
  973. ny = Math.Min (ny, maxDimension);
  974. if (viewToMove?.Frame.Height <= maxDimension)
  975. {
  976. ny = ny + viewToMove.Frame.Height > maxDimension
  977. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  978. : ny;
  979. //if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  980. //{
  981. // ny = Math.Max (viewToMove.Frame.Bottom, 0);
  982. //}
  983. }
  984. else
  985. {
  986. ny = 0;
  987. }
  988. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  989. return superView!;
  990. }
  991. /// <summary>
  992. /// Gets the Views that are under <paramref name="screenLocation"/>, including Adornments. The list is ordered by depth. The
  993. /// deepest
  994. /// View is at the end of the list (the top most View is at element 0).
  995. /// </summary>
  996. /// <param name="screenLocation">Screen-relative location.</param>
  997. /// <param name="excludeViewportSettingsFlags">
  998. /// If set, excludes Views that have the <see cref="ViewportSettingsFlags.Transparent"/> or <see cref="ViewportSettingsFlags.TransparentMouse"/>
  999. /// flags set in their ViewportSettings.
  1000. /// </param>
  1001. public static List<View?> GetViewsUnderLocation (in Point screenLocation, ViewportSettingsFlags excludeViewportSettingsFlags)
  1002. {
  1003. // PopoverHost - If visible, start with it instead of Top
  1004. if (Application.Popover?.GetActivePopover () is View { Visible: true } visiblePopover)
  1005. {
  1006. // BUGBUG: We do not traverse all visible toplevels if there's an active popover. This may be a bug.
  1007. List<View?> result = [];
  1008. result.AddRange (GetViewsUnderLocation (visiblePopover, screenLocation, excludeViewportSettingsFlags));
  1009. if (result.Count > 0)
  1010. {
  1011. return result;
  1012. }
  1013. }
  1014. var checkedTop = false;
  1015. // Traverse all visible toplevels, topmost first (reverse stack order)
  1016. if (Application.TopLevels.Count > 0)
  1017. {
  1018. foreach (Toplevel toplevel in Application.TopLevels)
  1019. {
  1020. if (toplevel.Visible && toplevel.Contains (screenLocation))
  1021. {
  1022. List<View?> result = GetViewsUnderLocation (toplevel, screenLocation, excludeViewportSettingsFlags);
  1023. // Only return if the result is not empty
  1024. if (result.Count > 0)
  1025. {
  1026. return result;
  1027. }
  1028. }
  1029. if (toplevel == Application.Top)
  1030. {
  1031. checkedTop = true;
  1032. }
  1033. }
  1034. }
  1035. // Fallback: If TopLevels is empty or Top is not in TopLevels, check Top directly (for test compatibility)
  1036. if (!checkedTop && Application.Top is { Visible: true } top)
  1037. {
  1038. // For root toplevels, allow hit-testing even if location is outside bounds (for drag/move)
  1039. List<View?> result = GetViewsUnderLocation (top, screenLocation, excludeViewportSettingsFlags);
  1040. if (result.Count > 0)
  1041. {
  1042. return result;
  1043. }
  1044. }
  1045. return [];
  1046. }
  1047. /// <summary>
  1048. /// INTERNAL: Helper for GetViewsUnderLocation that starts from a given root view.
  1049. /// Gets the Views that are under <paramref name="screenLocation"/>, including Adornments. The list is ordered by depth. The
  1050. /// deepest
  1051. /// View is at the end of the list (the topmost View is at element 0).
  1052. /// </summary>
  1053. /// <param name="root"></param>
  1054. /// <param name="screenLocation">Screen-relative location.</param>
  1055. /// <param name="excludeViewportSettingsFlags">
  1056. /// If set, excludes Views that have the <see cref="ViewportSettingsFlags.Transparent"/> or <see cref="ViewportSettingsFlags.TransparentMouse"/>
  1057. /// flags set in their ViewportSettings.
  1058. /// </param>
  1059. internal static List<View?> GetViewsUnderLocation (View root, in Point screenLocation, ViewportSettingsFlags excludeViewportSettingsFlags)
  1060. {
  1061. List<View?> viewsUnderLocation = GetViewsAtLocation (root, screenLocation);
  1062. if (!excludeViewportSettingsFlags.HasFlag (ViewportSettingsFlags.Transparent) && !excludeViewportSettingsFlags.HasFlag (ViewportSettingsFlags.TransparentMouse))
  1063. {
  1064. // Only filter views if we are excluding transparent views.
  1065. return viewsUnderLocation;
  1066. }
  1067. // Remove all views that have an adornment with ViewportSettings.TransparentMouse; they are in the list
  1068. // because the point was in their adornment, and if the adornment is transparent, they should be removed.
  1069. viewsUnderLocation.RemoveAll (
  1070. v =>
  1071. {
  1072. if (v is null or Adornment)
  1073. {
  1074. return false;
  1075. }
  1076. bool? ret = null;
  1077. if (viewsUnderLocation.Contains (v.Margin)
  1078. && v.Margin!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1079. {
  1080. ret = true;
  1081. }
  1082. if (viewsUnderLocation.Contains (v.Border)
  1083. && v.Border!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1084. {
  1085. ret = true;
  1086. }
  1087. if (viewsUnderLocation.Contains (v.Padding)
  1088. && v.Padding!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1089. {
  1090. ret = true;
  1091. }
  1092. return ret is true;
  1093. });
  1094. // Now remove all views that have ViewportSettings.TransparentMouse set
  1095. viewsUnderLocation.RemoveAll (v => v!.ViewportSettings.HasFlag (excludeViewportSettingsFlags));
  1096. return viewsUnderLocation;
  1097. }
  1098. /// <summary>
  1099. /// INTERNAL: Gets ALL Views (Subviews and Adornments) in the of <see cref="SuperView"/> hierarchcy that are at
  1100. /// <paramref name="location"/>,
  1101. /// regardless of whether they will be drawn or see mouse events or not. Views with <see cref="Visible"/> set to
  1102. /// <see langword="false"/> will not be included.
  1103. /// The list is ordered by depth. The deepest View is at the end of the list (the topmost View is at element 0).
  1104. /// </summary>
  1105. /// <param name="superView">The root view from which the search for subviews begins.</param>
  1106. /// <param name="location">The screen-relative location where the search for views is focused.</param>
  1107. /// <returns>A list of views that are located under the specified point.</returns>
  1108. internal static List<View?> GetViewsAtLocation (View? superView, in Point location)
  1109. {
  1110. if (superView is null || !superView.Visible)
  1111. {
  1112. return [];
  1113. }
  1114. List<View?> result = [];
  1115. Stack<View> viewsToProcess = new ();
  1116. // Start with the superview if it contains the location
  1117. if (superView.FrameToScreen ().Contains (location))
  1118. {
  1119. viewsToProcess.Push (superView);
  1120. }
  1121. while (viewsToProcess.Count > 0)
  1122. {
  1123. View currentView = viewsToProcess.Pop ();
  1124. // Add the current view to the result
  1125. result.Add (currentView);
  1126. // Add adornments for the current view
  1127. result.AddRange (Adornment.GetViewsAtLocation (currentView.Margin, location));
  1128. result.AddRange (Adornment.GetViewsAtLocation (currentView.Border, location));
  1129. result.AddRange (Adornment.GetViewsAtLocation (currentView.Padding, location));
  1130. // Add subviews to the stack in reverse order
  1131. // This maintains the original depth-first traversal order
  1132. for (int i = currentView.InternalSubViews.Count - 1; i >= 0; i--)
  1133. {
  1134. View subview = currentView.InternalSubViews [i];
  1135. if (subview.Visible && subview.FrameToScreen ().Contains (location))
  1136. {
  1137. viewsToProcess.Push (subview);
  1138. }
  1139. }
  1140. }
  1141. return result;
  1142. }
  1143. #endregion Utilities
  1144. #region Diagnostics and Verification
  1145. // Diagnostics to highlight when X or Y is read before the view has been initialized
  1146. private Pos VerifyIsInitialized (Pos pos, string member)
  1147. {
  1148. //#if DEBUG
  1149. // if (pos.ReferencesOtherViews () && !IsInitialized)
  1150. // {
  1151. // Debug.WriteLine (
  1152. // $"WARNING: {member} = {pos} of {this} is dependent on other views and {member} "
  1153. // + $"is being accessed before the View has been initialized. This is likely a bug."
  1154. // );
  1155. // }
  1156. //#endif // DEBUG
  1157. return pos;
  1158. }
  1159. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  1160. private Dim? VerifyIsInitialized (Dim? dim, string member)
  1161. {
  1162. //#if DEBUG
  1163. // if (dim.ReferencesOtherViews () && !IsInitialized)
  1164. // {
  1165. // Debug.WriteLine (
  1166. // $"WARNING: {member} = {dim} of {this} is dependent on other views and {member} "
  1167. // + $"is being accessed before the View has been initialized. This is likely a bug."
  1168. // );
  1169. // }
  1170. //#endif // DEBUG
  1171. return dim;
  1172. }
  1173. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  1174. /// <remarks>
  1175. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  1176. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubViews"/>. If invalid
  1177. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  1178. /// thus should only be used for debugging.
  1179. /// </remarks>
  1180. public bool ValidatePosDim { get; set; }
  1181. // TODO: Move this logic into the Pos/Dim classes
  1182. /// <summary>
  1183. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  1184. /// Views dimensions.
  1185. /// </summary>
  1186. /// <exception cref="InvalidOperationException"></exception>
  1187. private void CheckDimAuto ()
  1188. {
  1189. if (!ValidatePosDim || !IsInitialized)
  1190. {
  1191. return;
  1192. }
  1193. var widthAuto = Width as DimAuto;
  1194. var heightAuto = Height as DimAuto;
  1195. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  1196. foreach (View view in SubViews)
  1197. {
  1198. if (widthAuto is { } && widthAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  1199. {
  1200. ThrowInvalid (view, view.Width, nameof (view.Width));
  1201. ThrowInvalid (view, view.X, nameof (view.X));
  1202. }
  1203. if (heightAuto is { } && heightAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  1204. {
  1205. ThrowInvalid (view, view.Height, nameof (view.Height));
  1206. ThrowInvalid (view, view.Y, nameof (view.Y));
  1207. }
  1208. }
  1209. return;
  1210. void ThrowInvalid (View view, object? checkPosDim, string name)
  1211. {
  1212. object? bad = null;
  1213. switch (checkPosDim)
  1214. {
  1215. case Pos pos and PosAnchorEnd:
  1216. break;
  1217. case Pos pos and not PosAbsolute and not PosView and not PosCombine:
  1218. bad = pos;
  1219. break;
  1220. case Pos pos and PosCombine:
  1221. // Recursively check for not Absolute or not View
  1222. ThrowInvalid (view, (pos as PosCombine)?.Left, name);
  1223. ThrowInvalid (view, (pos as PosCombine)?.Right, name);
  1224. break;
  1225. case Dim dim and DimAuto:
  1226. break;
  1227. case Dim dim and DimFill:
  1228. break;
  1229. case Dim dim and not DimAbsolute and not DimView and not DimCombine:
  1230. bad = dim;
  1231. break;
  1232. case Dim dim and DimCombine:
  1233. // Recursively check for not Absolute or not View
  1234. ThrowInvalid (view, (dim as DimCombine)?.Left, name);
  1235. ThrowInvalid (view, (dim as DimCombine)?.Right, name);
  1236. break;
  1237. }
  1238. if (bad != null)
  1239. {
  1240. throw new LayoutException (
  1241. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  1242. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  1243. );
  1244. }
  1245. }
  1246. }
  1247. #endregion Diagnostics and Verification
  1248. }