View.Layout.cs 59 KB

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