View.Layout.cs 59 KB

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