View.Layout.cs 60 KB

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