View.Layout.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  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. if (viewToMove?.SuperView is null || viewToMove == app?.TopRunnable || viewToMove?.SuperView == app?.TopRunnable)
  1030. {
  1031. menuVisible = app?.TopRunnable?.MenuBar?.Visible == true;
  1032. }
  1033. else
  1034. {
  1035. View? t = viewToMove!.SuperView;
  1036. while (t is { } and not Toplevel)
  1037. {
  1038. t = t.SuperView;
  1039. }
  1040. if (t is Toplevel topLevel)
  1041. {
  1042. menuVisible = topLevel.MenuBar?.Visible == true;
  1043. }
  1044. }
  1045. if (viewToMove?.SuperView is null || viewToMove == app?.TopRunnable || viewToMove?.SuperView == app?.TopRunnable)
  1046. {
  1047. maxDimension = menuVisible ? 1 : 0;
  1048. }
  1049. else
  1050. {
  1051. maxDimension = 0;
  1052. }
  1053. ny = Math.Max (targetY, maxDimension);
  1054. if (viewToMove?.SuperView is null || viewToMove == app?.TopRunnable || viewToMove?.SuperView == app?.TopRunnable)
  1055. {
  1056. if (app is { })
  1057. {
  1058. maxDimension = statusVisible ? app.Screen.Height - 1 : app.Screen.Height;
  1059. }
  1060. else
  1061. {
  1062. maxDimension = 0;
  1063. }
  1064. }
  1065. else
  1066. {
  1067. maxDimension = statusVisible ? viewToMove!.SuperView.Viewport.Height - 1 : viewToMove!.SuperView.Viewport.Height;
  1068. }
  1069. if (superView?.Margin is { } && superView == viewToMove?.SuperView)
  1070. {
  1071. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  1072. }
  1073. ny = Math.Min (ny, maxDimension);
  1074. if (viewToMove?.Frame.Height <= maxDimension)
  1075. {
  1076. ny = ny + viewToMove.Frame.Height > maxDimension
  1077. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  1078. : ny;
  1079. //if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  1080. //{
  1081. // ny = Math.Max (viewToMove.Frame.Bottom, 0);
  1082. //}
  1083. }
  1084. else
  1085. {
  1086. ny = 0;
  1087. }
  1088. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  1089. return superView!;
  1090. }
  1091. /// <summary>
  1092. /// Gets the Views that are under <paramref name="screenLocation"/>, including Adornments. The list is ordered by
  1093. /// depth. The
  1094. /// deepest
  1095. /// View is at the end of the list (the top most View is at element 0).
  1096. /// </summary>
  1097. /// <param name="screenLocation">Screen-relative location.</param>
  1098. /// <param name="excludeViewportSettingsFlags">
  1099. /// If set, excludes Views that have the <see cref="ViewportSettingsFlags.Transparent"/> or
  1100. /// <see cref="ViewportSettingsFlags.TransparentMouse"/>
  1101. /// flags set in their ViewportSettings.
  1102. /// </param>
  1103. public List<View?> GetViewsUnderLocation (in Point screenLocation, ViewportSettingsFlags excludeViewportSettingsFlags)
  1104. {
  1105. // PopoverHost - If visible, start with it instead of Top
  1106. if (App?.Popover?.GetActivePopover () is View { Visible: true } visiblePopover)
  1107. {
  1108. // BUGBUG: We do not traverse all visible toplevels if there's an active popover. This may be a bug.
  1109. List<View?> result = [];
  1110. result.AddRange (GetViewsUnderLocation (visiblePopover, screenLocation, excludeViewportSettingsFlags));
  1111. if (result.Count > 0)
  1112. {
  1113. return result;
  1114. }
  1115. }
  1116. var checkedTop = false;
  1117. // Traverse all visible toplevels, topmost first (reverse stack order)
  1118. if (App?.SessionStack.Count > 0)
  1119. {
  1120. foreach (Toplevel toplevel in App.SessionStack)
  1121. {
  1122. if (toplevel.Visible && toplevel.Contains (screenLocation))
  1123. {
  1124. List<View?> result = GetViewsUnderLocation (toplevel, screenLocation, excludeViewportSettingsFlags);
  1125. // Only return if the result is not empty
  1126. if (result.Count > 0)
  1127. {
  1128. return result;
  1129. }
  1130. }
  1131. if (toplevel == App.TopRunnable)
  1132. {
  1133. checkedTop = true;
  1134. }
  1135. }
  1136. }
  1137. // Fallback: If TopLevels is empty or Top is not in TopLevels, check Top directly (for test compatibility)
  1138. if (!checkedTop && App?.TopRunnable is { Visible: true } top)
  1139. {
  1140. // For root toplevels, allow hit-testing even if location is outside bounds (for drag/move)
  1141. List<View?> result = GetViewsUnderLocation (top, screenLocation, excludeViewportSettingsFlags);
  1142. if (result.Count > 0)
  1143. {
  1144. return result;
  1145. }
  1146. }
  1147. return [];
  1148. }
  1149. /// <summary>
  1150. /// INTERNAL: Helper for GetViewsUnderLocation that starts from a given root view.
  1151. /// Gets the Views that are under <paramref name="screenLocation"/>, including Adornments. The list is ordered by
  1152. /// depth. The
  1153. /// deepest
  1154. /// View is at the end of the list (the topmost View is at element 0).
  1155. /// </summary>
  1156. /// <param name="root"></param>
  1157. /// <param name="screenLocation">Screen-relative location.</param>
  1158. /// <param name="excludeViewportSettingsFlags">
  1159. /// If set, excludes Views that have the <see cref="ViewportSettingsFlags.Transparent"/> or
  1160. /// <see cref="ViewportSettingsFlags.TransparentMouse"/>
  1161. /// flags set in their ViewportSettings.
  1162. /// </param>
  1163. internal static List<View?> GetViewsUnderLocation (View root, in Point screenLocation, ViewportSettingsFlags excludeViewportSettingsFlags)
  1164. {
  1165. List<View?> viewsUnderLocation = GetViewsAtLocation (root, screenLocation);
  1166. if (!excludeViewportSettingsFlags.HasFlag (ViewportSettingsFlags.Transparent)
  1167. && !excludeViewportSettingsFlags.HasFlag (ViewportSettingsFlags.TransparentMouse))
  1168. {
  1169. // Only filter views if we are excluding transparent views.
  1170. return viewsUnderLocation;
  1171. }
  1172. // Remove all views that have an adornment with ViewportSettings.TransparentMouse; they are in the list
  1173. // because the point was in their adornment, and if the adornment is transparent, they should be removed.
  1174. viewsUnderLocation.RemoveAll (v =>
  1175. {
  1176. if (v is null or Adornment)
  1177. {
  1178. return false;
  1179. }
  1180. bool? ret = null;
  1181. if (viewsUnderLocation.Contains (v.Margin)
  1182. && v.Margin!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1183. {
  1184. ret = true;
  1185. }
  1186. if (viewsUnderLocation.Contains (v.Border)
  1187. && v.Border!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1188. {
  1189. ret = true;
  1190. }
  1191. if (viewsUnderLocation.Contains (v.Padding)
  1192. && v.Padding!.ViewportSettings.HasFlag (excludeViewportSettingsFlags))
  1193. {
  1194. ret = true;
  1195. }
  1196. return ret is true;
  1197. });
  1198. // Now remove all views that have ViewportSettings.TransparentMouse set
  1199. viewsUnderLocation.RemoveAll (v => v!.ViewportSettings.HasFlag (excludeViewportSettingsFlags));
  1200. return viewsUnderLocation;
  1201. }
  1202. /// <summary>
  1203. /// INTERNAL: Gets ALL Views (Subviews and Adornments) in the of <see cref="SuperView"/> hierarchcy that are at
  1204. /// <paramref name="location"/>,
  1205. /// regardless of whether they will be drawn or see mouse events or not. Views with <see cref="Visible"/> set to
  1206. /// <see langword="false"/> will not be included.
  1207. /// The list is ordered by depth. The deepest View is at the end of the list (the topmost View is at element 0).
  1208. /// </summary>
  1209. /// <param name="superView">The root view from which the search for subviews begins.</param>
  1210. /// <param name="location">The screen-relative location where the search for views is focused.</param>
  1211. /// <returns>A list of views that are located under the specified point.</returns>
  1212. internal static List<View?> GetViewsAtLocation (View? superView, in Point location)
  1213. {
  1214. if (superView is null || !superView.Visible)
  1215. {
  1216. return [];
  1217. }
  1218. List<View?> result = [];
  1219. Stack<View> viewsToProcess = new ();
  1220. // Start with the superview if it contains the location
  1221. if (superView.FrameToScreen ().Contains (location))
  1222. {
  1223. viewsToProcess.Push (superView);
  1224. }
  1225. while (viewsToProcess.Count > 0)
  1226. {
  1227. View currentView = viewsToProcess.Pop ();
  1228. // Add the current view to the result
  1229. result.Add (currentView);
  1230. // Add adornments for the current view
  1231. result.AddRange (Adornment.GetViewsAtLocation (currentView.Margin, location));
  1232. result.AddRange (Adornment.GetViewsAtLocation (currentView.Border, location));
  1233. result.AddRange (Adornment.GetViewsAtLocation (currentView.Padding, location));
  1234. // Add subviews to the stack in reverse order
  1235. // This maintains the original depth-first traversal order
  1236. for (int i = currentView.InternalSubViews.Count - 1; i >= 0; i--)
  1237. {
  1238. View subview = currentView.InternalSubViews [i];
  1239. if (subview.Visible && subview.FrameToScreen ().Contains (location))
  1240. {
  1241. viewsToProcess.Push (subview);
  1242. }
  1243. }
  1244. }
  1245. return result;
  1246. }
  1247. #endregion Utilities
  1248. #region Diagnostics and Verification
  1249. // Diagnostics to highlight when X or Y is read before the view has been initialized
  1250. private Pos VerifyIsInitialized (Pos pos, string member)
  1251. {
  1252. //#if DEBUG
  1253. // if (pos.ReferencesOtherViews () && !IsInitialized)
  1254. // {
  1255. // Debug.WriteLine (
  1256. // $"WARNING: {member} = {pos} of {this} is dependent on other views and {member} "
  1257. // + $"is being accessed before the View has been initialized. This is likely a bug."
  1258. // );
  1259. // }
  1260. //#endif // DEBUG
  1261. return pos;
  1262. }
  1263. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  1264. private Dim VerifyIsInitialized (Dim dim, string member)
  1265. {
  1266. //#if DEBUG
  1267. // if (dim.ReferencesOtherViews () && !IsInitialized)
  1268. // {
  1269. // Debug.WriteLine (
  1270. // $"WARNING: {member} = {dim} of {this} is dependent on other views and {member} "
  1271. // + $"is being accessed before the View has been initialized. This is likely a bug."
  1272. // );
  1273. // }
  1274. //#endif // DEBUG
  1275. return dim;
  1276. }
  1277. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  1278. /// <remarks>
  1279. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  1280. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubViews"/>. If invalid
  1281. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  1282. /// thus should only be used for debugging.
  1283. /// </remarks>
  1284. public bool ValidatePosDim { get; set; }
  1285. // TODO: Move this logic into the Pos/Dim classes
  1286. /// <summary>
  1287. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  1288. /// Views dimensions.
  1289. /// </summary>
  1290. /// <exception cref="InvalidOperationException"></exception>
  1291. private void CheckDimAuto ()
  1292. {
  1293. if (!ValidatePosDim || !IsInitialized)
  1294. {
  1295. return;
  1296. }
  1297. var widthAuto = Width as DimAuto;
  1298. var heightAuto = Height as DimAuto;
  1299. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  1300. foreach (View view in SubViews)
  1301. {
  1302. if (widthAuto is { } && widthAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  1303. {
  1304. ThrowInvalid (view, view.Width, nameof (view.Width));
  1305. ThrowInvalid (view, view.X, nameof (view.X));
  1306. }
  1307. if (heightAuto is { } && heightAuto.Style.FastHasFlags (DimAutoStyle.Content) && ContentSizeTracksViewport)
  1308. {
  1309. ThrowInvalid (view, view.Height, nameof (view.Height));
  1310. ThrowInvalid (view, view.Y, nameof (view.Y));
  1311. }
  1312. }
  1313. return;
  1314. void ThrowInvalid (View view, object? checkPosDim, string name)
  1315. {
  1316. object? bad = null;
  1317. switch (checkPosDim)
  1318. {
  1319. case Pos pos and PosAnchorEnd:
  1320. break;
  1321. case Pos pos and not PosAbsolute and not PosView and not PosCombine:
  1322. bad = pos;
  1323. break;
  1324. case Pos pos and PosCombine:
  1325. // Recursively check for not Absolute or not View
  1326. ThrowInvalid (view, (pos as PosCombine)?.Left, name);
  1327. ThrowInvalid (view, (pos as PosCombine)?.Right, name);
  1328. break;
  1329. case Dim dim and DimAuto:
  1330. break;
  1331. case Dim dim and DimFill:
  1332. break;
  1333. case Dim dim and not DimAbsolute and not DimView and not DimCombine:
  1334. bad = dim;
  1335. break;
  1336. case Dim dim and DimCombine:
  1337. // Recursively check for not Absolute or not View
  1338. ThrowInvalid (view, (dim as DimCombine)?.Left, name);
  1339. ThrowInvalid (view, (dim as DimCombine)?.Right, name);
  1340. break;
  1341. }
  1342. if (bad != null)
  1343. {
  1344. throw new LayoutException (
  1345. $"{view.GetType ().Name}.{name} = {bad.GetType ().Name} "
  1346. + $"which depends on the SuperView's dimensions and the SuperView uses Dim.Auto."
  1347. );
  1348. }
  1349. }
  1350. }
  1351. #endregion Diagnostics and Verification
  1352. }