View.Layout.cs 59 KB

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