View.Layout.cs 59 KB

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