View.Layout.cs 60 KB

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