ViewLayout.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. using System.Diagnostics;
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// <para>Indicates the LayoutStyle for the <see cref="View"/>.</para>
  5. /// <para>
  6. /// If Absolute, the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  7. /// <see cref="View.Height"/> objects are all absolute values and are not relative. The position and size of the
  8. /// view is described by <see cref="View.Frame"/>.
  9. /// </para>
  10. /// <para>
  11. /// If Computed, one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  12. /// <see cref="View.Height"/> objects are relative to the <see cref="View.SuperView"/> and are computed at layout
  13. /// time.
  14. /// </para>
  15. /// </summary>
  16. public enum LayoutStyle
  17. {
  18. /// <summary>
  19. /// Indicates the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  20. /// <see cref="View.Height"/> objects are all absolute values and are not relative. The position and size of the view
  21. /// is described by <see cref="View.Frame"/>.
  22. /// </summary>
  23. Absolute,
  24. /// <summary>
  25. /// Indicates one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  26. /// <see cref="View.Height"/>
  27. /// objects are relative to the <see cref="View.SuperView"/> and are computed at layout time. The position and size of
  28. /// the
  29. /// view
  30. /// will be computed based on these objects at layout time. <see cref="View.Frame"/> will provide the absolute computed
  31. /// values.
  32. /// </summary>
  33. Computed
  34. }
  35. public partial class View
  36. {
  37. #region Frame
  38. private Rectangle _frame;
  39. /// <summary>Gets or sets the absolute location and dimension of the view.</summary>
  40. /// <value>
  41. /// The rectangle describing absolute location and dimension of the view, in coordinates relative to the
  42. /// <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.
  43. /// </value>
  44. /// <remarks>
  45. /// <para>Frame is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.</para>
  46. /// <para>
  47. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> to the
  48. /// values of the corresponding properties of the <paramref name="value"/> parameter.
  49. /// This causes <see cref="LayoutStyle"/> to be <see cref="LayoutStyle.Absolute"/>.
  50. /// </para>
  51. /// <para>
  52. /// Altering the Frame will eventually (when the view hierarchy is next laid out via see
  53. /// cref="LayoutSubviews"/>) cause <see cref="LayoutSubview(View, Size)"/> and
  54. /// <see cref="OnDrawContent(Rectangle)"/>
  55. /// methods to be called.
  56. /// </para>
  57. /// </remarks>
  58. public Rectangle Frame
  59. {
  60. get => _frame;
  61. set
  62. {
  63. if (_frame == value)
  64. {
  65. return;
  66. }
  67. SetFrame (value with { Width = Math.Max (value.Width, 0), Height = Math.Max (value.Height, 0) });
  68. // If Frame gets set, by definition, the View is now LayoutStyle.Absolute, so
  69. // set all Pos/Dim to Absolute values.
  70. _x = _frame.X;
  71. _y = _frame.Y;
  72. _width = _frame.Width;
  73. _height = _frame.Height;
  74. // TODO: Figure out if the below can be optimized.
  75. if (IsInitialized)
  76. {
  77. OnResizeNeeded ();
  78. }
  79. }
  80. }
  81. private void SetFrame (Rectangle frame)
  82. {
  83. var oldViewport = Rectangle.Empty;
  84. if (IsInitialized)
  85. {
  86. oldViewport = Viewport;
  87. }
  88. // This is the only place where _frame should be set directly. Use Frame = or SetFrame instead.
  89. _frame = frame;
  90. OnViewportChanged (new (IsInitialized ? Viewport : Rectangle.Empty, oldViewport));
  91. }
  92. /// <summary>Gets the <see cref="Frame"/> with a screen-relative location.</summary>
  93. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  94. public virtual Rectangle FrameToScreen ()
  95. {
  96. Rectangle screen = Frame;
  97. View current = SuperView;
  98. while (current is { })
  99. {
  100. if (current is Adornment adornment)
  101. {
  102. // Adornments don't have SuperViews; use Adornment.FrameToScreen override
  103. // which will give us the screen coordinates of the parent
  104. Rectangle parentScreen = adornment.FrameToScreen ();
  105. // Now add our Frame location
  106. parentScreen.Offset (screen.X, screen.Y);
  107. return parentScreen;
  108. }
  109. Point viewportOffset = current.GetViewportOffsetFromFrame ();
  110. viewportOffset.Offset (current.Frame.X - current.Viewport.X, current.Frame.Y - current.Viewport.Y);
  111. screen.X += viewportOffset.X;
  112. screen.Y += viewportOffset.Y;
  113. current = current.SuperView;
  114. }
  115. return screen;
  116. }
  117. /// <summary>
  118. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means relative to the
  119. /// View's <see cref="SuperView"/>'s <see cref="Viewport"/>.
  120. /// </summary>
  121. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Viewport"/>.</returns>
  122. /// <param name="x">Screen-relative column.</param>
  123. /// <param name="y">Screen-relative row.</param>
  124. public virtual Point ScreenToFrame (int x, int y)
  125. {
  126. if (SuperView is null)
  127. {
  128. return new (x - Frame.X, y - Frame.Y);
  129. }
  130. Point superViewViewportOffset = SuperView.GetViewportOffsetFromFrame ();
  131. superViewViewportOffset.X -= SuperView.Viewport.X;
  132. superViewViewportOffset.Y -= SuperView.Viewport.Y;
  133. x -= superViewViewportOffset.X;
  134. y -= superViewViewportOffset.Y;
  135. Point frame = SuperView.ScreenToFrame (x, y);
  136. frame.X -= Frame.X;
  137. frame.Y -= Frame.Y;
  138. return frame;
  139. }
  140. private Pos _x = Pos.At (0);
  141. /// <summary>Gets or sets the X position for the view (the column).</summary>
  142. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  143. /// <remarks>
  144. /// <para>
  145. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.
  146. /// </para>
  147. /// <para>
  148. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  149. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Size)"/> has been
  150. /// called.
  151. /// </para>
  152. /// <para>
  153. /// Changing this property will eventually (when the view is next drawn) cause the
  154. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  155. /// </para>
  156. /// <para>
  157. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  158. /// <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  159. /// </para>
  160. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  161. /// </remarks>
  162. public Pos X
  163. {
  164. get => VerifyIsInitialized (_x, nameof (X));
  165. set
  166. {
  167. if (Equals (_x, value))
  168. {
  169. return;
  170. }
  171. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  172. OnResizeNeeded ();
  173. }
  174. }
  175. private Pos _y = Pos.At (0);
  176. /// <summary>Gets or sets the Y position for the view (the row).</summary>
  177. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  178. /// <remarks>
  179. /// <para>
  180. /// The position is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>.
  181. /// </para>
  182. /// <para>
  183. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  184. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Size)"/> has been
  185. /// called.
  186. /// </para>
  187. /// <para>
  188. /// Changing this property will eventually (when the view is next drawn) cause the
  189. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  190. /// </para>
  191. /// <para>
  192. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  193. /// <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  194. /// </para>
  195. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  196. /// </remarks>
  197. public Pos Y
  198. {
  199. get => VerifyIsInitialized (_y, nameof (Y));
  200. set
  201. {
  202. if (Equals (_y, value))
  203. {
  204. return;
  205. }
  206. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  207. OnResizeNeeded ();
  208. }
  209. }
  210. private Dim _height = Dim.Sized (0);
  211. /// <summary>Gets or sets the height dimension of the view.</summary>
  212. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  213. /// <remarks>
  214. /// <para>
  215. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>
  216. /// .
  217. /// </para>
  218. /// <para>
  219. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the view has
  220. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Size)"/> has been
  221. /// called.
  222. /// </para>
  223. /// <para>
  224. /// Changing this property will eventually (when the view is next drawn) cause the
  225. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  226. /// </para>
  227. /// <para>
  228. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  229. /// <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  230. /// </para>
  231. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  232. /// </remarks>
  233. public Dim Height
  234. {
  235. get => VerifyIsInitialized (_height, nameof (Height));
  236. set
  237. {
  238. if (Equals (_height, value))
  239. {
  240. return;
  241. }
  242. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  243. OnResizeNeeded ();
  244. }
  245. }
  246. private Dim _width = Dim.Sized (0);
  247. /// <summary>Gets or sets the width dimension of the view.</summary>
  248. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  249. /// <remarks>
  250. /// <para>
  251. /// The dimension is relative to the <see cref="SuperView"/>'s Content, which is bound by <see cref="ContentSize"/>
  252. /// .
  253. /// </para>
  254. /// <para>
  255. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the view has
  256. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Size)"/> has been
  257. /// called.
  258. /// </para>
  259. /// <para>
  260. /// Changing this property will eventually (when the view is next drawn) cause the
  261. /// <see cref="LayoutSubview(View, Size)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  262. /// </para>
  263. /// <para>
  264. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  265. /// <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  266. /// </para>
  267. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  268. /// </remarks>
  269. public Dim Width
  270. {
  271. get => VerifyIsInitialized (_width, nameof (Width));
  272. set
  273. {
  274. if (Equals (_width, value))
  275. {
  276. return;
  277. }
  278. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  279. OnResizeNeeded ();
  280. }
  281. }
  282. #endregion Frame
  283. #region AutoSize
  284. /// <summary>
  285. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  286. /// within <see cref="Viewport"/>.
  287. /// <para>
  288. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If
  289. /// <see langword="true"/> then <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can
  290. /// fit; if <see cref="Text"/> won't fit the view will be resized as needed.
  291. /// </para>
  292. /// <para>
  293. /// If <see cref="AutoSize"/> is set to <see langword="true"/> then <see cref="Width"/> and <see cref="Height"/>
  294. /// will be changed to <see cref="Dim.DimAbsolute"/> if they are not already.
  295. /// </para>
  296. /// <para>
  297. /// If <see cref="AutoSize"/> is set to <see langword="false"/> then <see cref="Width"/> and <see cref="Height"/>
  298. /// will left unchanged.
  299. /// </para>
  300. /// </summary>
  301. public virtual bool AutoSize
  302. {
  303. get => _height is Dim.DimAuto && _width is Dim.DimAuto;
  304. set
  305. {
  306. if (IsInitialized)
  307. {
  308. Height = Dim.Auto (Dim.DimAutoStyle.Text);
  309. Width = Dim.Auto (Dim.DimAutoStyle.Text);
  310. }
  311. else
  312. {
  313. _height = Dim.Auto (Dim.DimAutoStyle.Text);
  314. _width = Dim.Auto (Dim.DimAutoStyle.Text);
  315. OnResizeNeeded();
  316. }
  317. }
  318. }
  319. ///// <summary>Determines if the View's <see cref="Height"/> can be set to a new value.</summary>
  320. ///// <remarks>TrySetHeight can only be called when AutoSize is true (or being set to true).</remarks>
  321. ///// <param name="desiredHeight"></param>
  322. ///// <param name="resultHeight">
  323. ///// Contains the width that would result if <see cref="Height"/> were set to
  324. ///// <paramref name="desiredHeight"/>"/>
  325. ///// </param>
  326. ///// <returns>
  327. ///// <see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False
  328. ///// otherwise.
  329. ///// </returns>
  330. //internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  331. //{
  332. // int h = desiredHeight;
  333. // bool canSetHeight;
  334. // switch (Height)
  335. // {
  336. // case Dim.DimCombine _:
  337. // case Dim.DimView _:
  338. // case Dim.DimFill _:
  339. // // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  340. // h = Height.Anchor (h);
  341. // canSetHeight = !ValidatePosDim;
  342. // break;
  343. // case Dim.DimFactor factor:
  344. // // Tries to get the SuperView height otherwise the view height.
  345. // int sh = SuperView is { } ? SuperView.Frame.Height : h;
  346. // if (factor.IsFromRemaining ())
  347. // {
  348. // sh -= Frame.Y;
  349. // }
  350. // h = Height.Anchor (sh);
  351. // canSetHeight = !ValidatePosDim;
  352. // break;
  353. // default:
  354. // canSetHeight = true;
  355. // break;
  356. // }
  357. // resultHeight = h;
  358. // return canSetHeight;
  359. //}
  360. ///// <summary>Determines if the View's <see cref="Width"/> can be set to a new value.</summary>
  361. ///// <remarks>TrySetWidth can only be called when AutoSize is true (or being set to true).</remarks>
  362. ///// <param name="desiredWidth"></param>
  363. ///// <param name="resultWidth">
  364. ///// Contains the width that would result if <see cref="Width"/> were set to
  365. ///// <paramref name="desiredWidth"/>"/>
  366. ///// </param>
  367. ///// <returns>
  368. ///// <see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False
  369. ///// otherwise.
  370. ///// </returns>
  371. //internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  372. //{
  373. // int w = desiredWidth;
  374. // bool canSetWidth;
  375. // switch (Width)
  376. // {
  377. // case Dim.DimCombine _:
  378. // case Dim.DimView _:
  379. // case Dim.DimFill _:
  380. // // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  381. // w = Width.Anchor (w);
  382. // canSetWidth = !ValidatePosDim;
  383. // break;
  384. // case Dim.DimFactor factor:
  385. // // Tries to get the SuperView Width otherwise the view Width.
  386. // int sw = SuperView is { } ? SuperView.Frame.Width : w;
  387. // if (factor.IsFromRemaining ())
  388. // {
  389. // sw -= Frame.X;
  390. // }
  391. // w = Width.Anchor (sw);
  392. // canSetWidth = !ValidatePosDim;
  393. // break;
  394. // default:
  395. // canSetWidth = true;
  396. // break;
  397. // }
  398. // resultWidth = w;
  399. // return canSetWidth;
  400. //}
  401. ///// <summary>Resizes the View to fit the specified size. Factors in the HotKey.</summary>
  402. ///// <remarks>ResizeBoundsToFit can only be called when AutoSize is true (or being set to true).</remarks>
  403. ///// <param name="size"></param>
  404. ///// <returns>whether the Viewport was changed or not</returns>
  405. //private bool ResizeViewportToFit (Size size)
  406. //{
  407. // //if (AutoSize == false) {
  408. // // throw new InvalidOperationException ("ResizeViewportToFit can only be called when AutoSize is true");
  409. // //}
  410. // var changed = false;
  411. // bool canSizeW = TrySetWidth (size.Width - GetHotKeySpecifierLength (), out int rW);
  412. // bool canSizeH = TrySetHeight (size.Height - GetHotKeySpecifierLength (false), out int rH);
  413. // if (canSizeW)
  414. // {
  415. // changed = true;
  416. // _width = rW;
  417. // }
  418. // if (canSizeH)
  419. // {
  420. // changed = true;
  421. // _height = rH;
  422. // }
  423. // if (changed)
  424. // {
  425. // Viewport = new (Viewport.X, Viewport.Y, canSizeW ? rW : Viewport.Width, canSizeH ? rH : Viewport.Height);
  426. // }
  427. // return changed;
  428. //}
  429. #endregion AutoSize
  430. #region Layout Engine
  431. /// <summary>
  432. /// Controls how the View's <see cref="Frame"/> is computed during <see cref="LayoutSubviews"/>. If the style is
  433. /// set to <see cref="LayoutStyle.Absolute"/>, LayoutSubviews does not change the <see cref="Frame"/>. If the style is
  434. /// <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using the <see cref="X"/>, <see cref="Y"/>,
  435. /// <see cref="Width"/>, and <see cref="Height"/> properties.
  436. /// </summary>
  437. /// <remarks>
  438. /// <para>
  439. /// Setting this property to <see cref="LayoutStyle.Absolute"/> will cause <see cref="Frame"/> to determine the
  440. /// size and position of the view. <see cref="X"/> and <see cref="Y"/> will be set to <see cref="Dim.DimAbsolute"/>
  441. /// using <see cref="Frame"/>.
  442. /// </para>
  443. /// <para>
  444. /// Setting this property to <see cref="LayoutStyle.Computed"/> will cause the view to use the
  445. /// <see cref="LayoutSubviews"/> method to size and position of the view. If either of the <see cref="X"/> and
  446. /// <see cref="Y"/> properties are `null` they will be set to <see cref="Pos.PosAbsolute"/> using the current value
  447. /// of <see cref="Frame"/>. If either of the <see cref="Width"/> and <see cref="Height"/> properties are `null`
  448. /// they will be set to <see cref="Dim.DimAbsolute"/> using <see cref="Frame"/>.
  449. /// </para>
  450. /// </remarks>
  451. /// <value>The layout style.</value>
  452. public LayoutStyle LayoutStyle
  453. {
  454. get
  455. {
  456. if (_x is Pos.PosAbsolute
  457. && _y is Pos.PosAbsolute
  458. && _width is Dim.DimAbsolute
  459. && _height is Dim.DimAbsolute)
  460. {
  461. return LayoutStyle.Absolute;
  462. }
  463. return LayoutStyle.Computed;
  464. }
  465. }
  466. #endregion Layout Engine
  467. /// <summary>
  468. /// Indicates whether the specified SuperView-relative coordinates are within the View's <see cref="Frame"/>.
  469. /// </summary>
  470. /// <param name="x">SuperView-relative X coordinate.</param>
  471. /// <param name="y">SuperView-relative Y coordinate.</param>
  472. /// <returns><see langword="true"/> if the specified SuperView-relative coordinates are within the View.</returns>
  473. public virtual bool Contains (int x, int y) { return Frame.Contains (x, y); }
  474. #nullable enable
  475. /// <summary>Finds the first Subview of <paramref name="start"/> that is visible at the provided location.</summary>
  476. /// <remarks>
  477. /// <para>
  478. /// Used to determine what view the mouse is over.
  479. /// </para>
  480. /// </remarks>
  481. /// <param name="start">The view to scope the search by.</param>
  482. /// <param name="x"><paramref name="start"/>.SuperView-relative X coordinate.</param>
  483. /// <param name="y"><paramref name="start"/>.SuperView-relative Y coordinate.</param>
  484. /// <returns>
  485. /// The view that was found at the <paramref name="x"/> and <paramref name="y"/> coordinates.
  486. /// <see langword="null"/> if no view was found.
  487. /// </returns>
  488. // CONCURRENCY: This method is not thread-safe. Undefined behavior and likely program crashes are exposed by unsynchronized access to InternalSubviews.
  489. internal static View? FindDeepestView (View? start, int x, int y)
  490. {
  491. while (start is { Visible: true } && start.Contains (x, y))
  492. {
  493. Adornment? found = null;
  494. if (start.Margin.Contains (x, y))
  495. {
  496. found = start.Margin;
  497. }
  498. else if (start.Border.Contains (x, y))
  499. {
  500. found = start.Border;
  501. }
  502. else if (start.Padding.Contains (x, y))
  503. {
  504. found = start.Padding;
  505. }
  506. Point viewportOffset = start.GetViewportOffsetFromFrame ();
  507. if (found is { })
  508. {
  509. start = found;
  510. viewportOffset = found.Parent.Frame.Location;
  511. }
  512. int startOffsetX = x - (start.Frame.X + viewportOffset.X);
  513. int startOffsetY = y - (start.Frame.Y + viewportOffset.Y);
  514. View? subview = null;
  515. for (int i = start.InternalSubviews.Count - 1; i >= 0; i--)
  516. {
  517. if (start.InternalSubviews [i].Visible
  518. && start.InternalSubviews [i].Contains (startOffsetX + start.Viewport.X, startOffsetY + start.Viewport.Y))
  519. {
  520. subview = start.InternalSubviews [i];
  521. x = startOffsetX + start.Viewport.X;
  522. y = startOffsetY + start.Viewport.Y;
  523. // start is the deepest subview under the mouse; stop searching the subviews
  524. break;
  525. }
  526. }
  527. if (subview is null)
  528. {
  529. // No subview was found that's under the mouse, so we're done
  530. return start;
  531. }
  532. // We found a subview of start that's under the mouse, continue...
  533. start = subview;
  534. }
  535. return null;
  536. }
  537. #nullable restore
  538. /// <summary>
  539. /// Gets a new location of the <see cref="View"/> that is within the Viewport of the <paramref name="viewToMove"/>'s
  540. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  541. /// </summary>
  542. /// <remarks>
  543. /// If <paramref name="viewToMove"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  544. /// <see cref="Application.Top"/> the position will be bound by the <see cref="ConsoleDriver.Cols"/> and
  545. /// <see cref="ConsoleDriver.Rows"/>.
  546. /// </remarks>
  547. /// <param name="viewToMove">The View that is to be moved.</param>
  548. /// <param name="targetX">The target x location.</param>
  549. /// <param name="targetY">The target y location.</param>
  550. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  551. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  552. /// <param name="statusBar">The new top most statusBar</param>
  553. /// <returns>
  554. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  555. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  556. /// </returns>
  557. internal static View GetLocationEnsuringFullVisibility (
  558. View viewToMove,
  559. int targetX,
  560. int targetY,
  561. out int nx,
  562. out int ny,
  563. out StatusBar statusBar
  564. )
  565. {
  566. int maxDimension;
  567. View superView;
  568. statusBar = null;
  569. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  570. {
  571. maxDimension = Driver.Cols;
  572. superView = Application.Top;
  573. }
  574. else
  575. {
  576. // Use the SuperView's Viewport, not Frame
  577. maxDimension = viewToMove.SuperView.Viewport.Width;
  578. superView = viewToMove.SuperView;
  579. }
  580. if (superView.Margin is { } && superView == viewToMove.SuperView)
  581. {
  582. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  583. }
  584. if (viewToMove.Frame.Width <= maxDimension)
  585. {
  586. nx = Math.Max (targetX, 0);
  587. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  588. if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  589. {
  590. nx = Math.Max (viewToMove.Frame.Right, 0);
  591. }
  592. }
  593. else
  594. {
  595. nx = targetX;
  596. }
  597. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  598. var menuVisible = false;
  599. var statusVisible = false;
  600. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  601. {
  602. menuVisible = Application.Top.MenuBar?.Visible == true;
  603. }
  604. else
  605. {
  606. View t = viewToMove.SuperView;
  607. while (t is { } and not Toplevel)
  608. {
  609. t = t.SuperView;
  610. }
  611. if (t is Toplevel toplevel)
  612. {
  613. menuVisible = toplevel.MenuBar?.Visible == true;
  614. }
  615. }
  616. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  617. {
  618. maxDimension = menuVisible ? 1 : 0;
  619. }
  620. else
  621. {
  622. maxDimension = 0;
  623. }
  624. ny = Math.Max (targetY, maxDimension);
  625. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  626. {
  627. statusVisible = Application.Top.StatusBar?.Visible == true;
  628. statusBar = Application.Top.StatusBar;
  629. }
  630. else
  631. {
  632. View t = viewToMove.SuperView;
  633. while (t is { } and not Toplevel)
  634. {
  635. t = t.SuperView;
  636. }
  637. if (t is Toplevel toplevel)
  638. {
  639. statusVisible = toplevel.StatusBar?.Visible == true;
  640. statusBar = toplevel.StatusBar;
  641. }
  642. }
  643. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  644. {
  645. maxDimension = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  646. }
  647. else
  648. {
  649. maxDimension = statusVisible ? viewToMove.SuperView.Viewport.Height - 1 : viewToMove.SuperView.Viewport.Height;
  650. }
  651. if (superView.Margin is { } && superView == viewToMove.SuperView)
  652. {
  653. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  654. }
  655. ny = Math.Min (ny, maxDimension);
  656. if (viewToMove.Frame.Height <= maxDimension)
  657. {
  658. ny = ny + viewToMove.Frame.Height > maxDimension
  659. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  660. : ny;
  661. if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  662. {
  663. ny = Math.Max (viewToMove.Frame.Bottom, 0);
  664. }
  665. }
  666. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  667. return superView;
  668. }
  669. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  670. /// <remarks>
  671. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  672. /// otherwise changed.
  673. /// </remarks>
  674. public event EventHandler<LayoutEventArgs> LayoutComplete;
  675. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  676. /// <remarks>
  677. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  678. /// otherwise changed.
  679. /// </remarks>
  680. public event EventHandler<LayoutEventArgs> LayoutStarted;
  681. /// <summary>
  682. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in response to
  683. /// the container view or terminal resizing.
  684. /// </summary>
  685. /// <remarks>
  686. /// <para>
  687. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  688. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  689. /// </para>
  690. /// <para>Raises the <see cref="LayoutComplete"/> event) before it returns.</para>
  691. /// </remarks>
  692. public virtual void LayoutSubviews ()
  693. {
  694. if (!IsInitialized)
  695. {
  696. Debug.WriteLine ($"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}");
  697. }
  698. if (!LayoutNeeded)
  699. {
  700. return;
  701. }
  702. CheckDimAuto ();
  703. LayoutAdornments ();
  704. OnLayoutStarted (new (ContentSize));
  705. SetTextFormatterSize ();
  706. // Sort out the dependencies of the X, Y, Width, Height properties
  707. HashSet<View> nodes = new ();
  708. HashSet<(View, View)> edges = new ();
  709. CollectAll (this, ref nodes, ref edges);
  710. List<View> ordered = TopologicalSort (SuperView, nodes, edges);
  711. foreach (View v in ordered)
  712. {
  713. // TODO: Move this logic into the Pos/Dim classes
  714. if (v.Width is Dim.DimAuto || v.Height is Dim.DimAuto)
  715. {
  716. // If the view is auto-sized...
  717. Rectangle f = v.Frame;
  718. v._frame = new (v.Frame.X, v.Frame.Y, 0, 0);
  719. LayoutSubview (v, Viewport.Size);
  720. if (v.Frame != f)
  721. {
  722. // The subviews changed; do it again
  723. v.LayoutNeeded = true;
  724. LayoutSubview (v, Viewport.Size);
  725. }
  726. }
  727. else
  728. {
  729. LayoutSubview (v, Viewport.Size);
  730. }
  731. }
  732. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  733. // Use LayoutSubview with the Frame of the 'from'
  734. if (SuperView is { } && GetTopSuperView () is { } && LayoutNeeded && edges.Count > 0)
  735. {
  736. foreach ((View from, View to) in edges)
  737. {
  738. LayoutSubview (to, from.ContentSize);
  739. }
  740. }
  741. LayoutNeeded = false;
  742. OnLayoutComplete (new (ContentSize));
  743. }
  744. // TODO: Move this logic into the Pos/Dim classes
  745. /// <summary>
  746. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  747. /// Views dimensions.
  748. /// </summary>
  749. /// <exception cref="InvalidOperationException"></exception>
  750. private void CheckDimAuto ()
  751. {
  752. if (!ValidatePosDim || !IsInitialized || (Width is not Dim.DimAuto && Height is not Dim.DimAuto))
  753. {
  754. return;
  755. }
  756. void ThrowInvalid (View view, object checkPosDim, string name)
  757. {
  758. // TODO: Figure out how to make CheckDimAuto deal with PosCombine
  759. object bad = null;
  760. switch (checkPosDim)
  761. {
  762. case Pos pos and not Pos.PosAbsolute and not Pos.PosView and not Pos.PosCombine:
  763. bad = pos;
  764. break;
  765. case Pos pos and Pos.PosCombine:
  766. // Recursively check for not Absolute or not View
  767. ThrowInvalid (view, (pos as Pos.PosCombine)._left, name);
  768. ThrowInvalid (view, (pos as Pos.PosCombine)._right, name);
  769. break;
  770. case Dim dim and not Dim.DimAbsolute and not Dim.DimView and not Dim.DimCombine:
  771. bad = dim;
  772. break;
  773. case Dim dim and Dim.DimCombine:
  774. // Recursively check for not Absolute or not View
  775. ThrowInvalid (view, (dim as Dim.DimCombine)._left, name);
  776. ThrowInvalid (view, (dim as Dim.DimCombine)._right, name);
  777. break;
  778. }
  779. if (bad != null)
  780. {
  781. throw new InvalidOperationException (
  782. @$"{view.GetType ().Name}.{name} = {bad.GetType ().Name} which depends on the SuperView's dimensions and the SuperView uses Dim.Auto.");
  783. }
  784. }
  785. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  786. foreach (View view in Subviews)
  787. {
  788. if (Width is Dim.DimAuto { _min: null })
  789. {
  790. ThrowInvalid (view, view.Width, nameof (view.Width));
  791. ThrowInvalid (view, view.X, nameof (view.X));
  792. }
  793. if (Height is Dim.DimAuto { _min: null })
  794. {
  795. ThrowInvalid (view, view.Height, nameof (view.Height));
  796. ThrowInvalid (view, view.Y, nameof (view.Y));
  797. }
  798. }
  799. }
  800. private void LayoutSubview (View v, Size contentSize)
  801. {
  802. v.SetRelativeLayout (contentSize);
  803. v.LayoutSubviews ();
  804. v.LayoutNeeded = false;
  805. }
  806. /// <summary>Indicates that the view does not need to be laid out.</summary>
  807. protected void ClearLayoutNeeded () { LayoutNeeded = false; }
  808. /// <summary>
  809. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views
  810. /// have been laid out.
  811. /// </summary>
  812. internal virtual void OnLayoutComplete (LayoutEventArgs args) { LayoutComplete?.Invoke (this, args); }
  813. /// <summary>
  814. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews
  815. /// have been laid out.
  816. /// </summary>
  817. internal virtual void OnLayoutStarted (LayoutEventArgs args) { LayoutStarted?.Invoke (this, args); }
  818. /// <summary>
  819. /// Called whenever the view needs to be resized. This is called whenever <see cref="Frame"/>,
  820. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or <see cref="View.Height"/> changes.
  821. /// </summary>
  822. /// <remarks>
  823. /// <para>
  824. /// Determines the relative bounds of the <see cref="View"/> and its <see cref="Frame"/>s, and then calls
  825. /// <see cref="SetRelativeLayout(Size)"/> to update the view.
  826. /// </para>
  827. /// </remarks>
  828. internal void OnResizeNeeded ()
  829. {
  830. // TODO: Identify a real-world use-case where this API should be virtual.
  831. // TODO: Until then leave it `internal` and non-virtual
  832. // First try SuperView.Viewport, then Application.Top, then Driver.Viewport.
  833. // Finally, if none of those are valid, use int.MaxValue (for Unit tests).
  834. Size contentSize = SuperView is { IsInitialized: true } ? SuperView.ContentSize :
  835. Application.Top is { } && Application.Top != this && Application.Top.IsInitialized ? Application.Top.ContentSize :
  836. Application.Driver?.Screen.Size ?? new (int.MaxValue, int.MaxValue);
  837. SetRelativeLayout (contentSize);
  838. // TODO: Determine what, if any of the below is actually needed here.
  839. if (IsInitialized)
  840. {
  841. if (AutoSize)
  842. {
  843. // SetFrameToFitText ();
  844. // SetTextFormatterSize ();
  845. }
  846. LayoutAdornments ();
  847. SetNeedsDisplay ();
  848. SetNeedsLayout ();
  849. }
  850. }
  851. internal bool LayoutNeeded { get; private set; } = true;
  852. /// <summary>
  853. /// Sets the internal <see cref="LayoutNeeded"/> flag for this View and all of it's subviews and it's SuperView.
  854. /// The main loop will call SetRelativeLayout and LayoutSubviews for any view with <see cref="LayoutNeeded"/> set.
  855. /// </summary>
  856. internal void SetNeedsLayout ()
  857. {
  858. if (LayoutNeeded)
  859. {
  860. return;
  861. }
  862. LayoutNeeded = true;
  863. foreach (View view in Subviews)
  864. {
  865. view.SetNeedsLayout ();
  866. }
  867. TextFormatter.NeedsFormat = true;
  868. SuperView?.SetNeedsLayout ();
  869. }
  870. /// <summary>
  871. /// Adjusts <see cref="Frame"/> given the SuperView's ContentSize (nominally the same as
  872. /// <c>this.SuperView.ContentSize</c>)
  873. /// and the position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  874. /// <see cref="Height"/>).
  875. /// </summary>
  876. /// <remarks>
  877. /// <para>
  878. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  879. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  880. /// are left unchanged.
  881. /// </para>
  882. /// </remarks>
  883. /// <param name="superviewContentSize">
  884. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.ContentSize</c>).
  885. /// </param>
  886. internal void SetRelativeLayout (Size superviewContentSize)
  887. {
  888. Debug.Assert (_x is { });
  889. Debug.Assert (_y is { });
  890. Debug.Assert (_width is { });
  891. Debug.Assert (_height is { });
  892. CheckDimAuto ();
  893. var autoSize = Size.Empty;
  894. //if (AutoSize)
  895. //{
  896. // // TODO: Nuke this from orbit once Dim.Auto is fully implemented
  897. // autoSize = GetTextAutoSize ();
  898. //}
  899. int newX = _x.Calculate (superviewContentSize.Width, _width, this, Dim.Dimension.Width, autoSize.Width, AutoSize);
  900. int newW = _width.Calculate (newX, superviewContentSize.Width, this, Dim.Dimension.Width, autoSize.Width, AutoSize);
  901. int newY = _y.Calculate (superviewContentSize.Height, _height, this, Dim.Dimension.Height, autoSize.Height, AutoSize);
  902. int newH = _height.Calculate (newY, superviewContentSize.Height, this, Dim.Dimension.Height, autoSize.Height, AutoSize);
  903. Rectangle newFrame = new (newX, newY, newW, newH);
  904. if (Frame != newFrame)
  905. {
  906. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  907. // the view LayoutStyle.Absolute.
  908. SetFrame (newFrame);
  909. if (_x is Pos.PosAbsolute)
  910. {
  911. _x = Frame.X;
  912. }
  913. if (_y is Pos.PosAbsolute)
  914. {
  915. _y = Frame.Y;
  916. }
  917. if (_width is Dim.DimAbsolute)
  918. {
  919. _width = Frame.Width;
  920. }
  921. if (_height is Dim.DimAbsolute)
  922. {
  923. _height = Frame.Height;
  924. }
  925. SetNeedsLayout ();
  926. SetNeedsDisplay ();
  927. }
  928. //if (AutoSize)
  929. //{
  930. // if (autoSize.Width == 0 || autoSize.Height == 0)
  931. // {
  932. // // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  933. // // the view LayoutStyle.Absolute.
  934. // SetFrame (_frame with { Size = autoSize });
  935. // if (autoSize.Width == 0)
  936. // {
  937. // _width = 0;
  938. // }
  939. // if (autoSize.Height == 0)
  940. // {
  941. // _height = 0;
  942. // }
  943. // }
  944. // //else if (!SetFrameToFitText ())
  945. // //{
  946. // // SetTextFormatterSize ();
  947. // //}
  948. // SetNeedsLayout ();
  949. // SetNeedsDisplay ();
  950. //}
  951. }
  952. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  953. {
  954. // BUGBUG: This should really only work on initialized subviews
  955. foreach (View v in from.InternalSubviews /*.Where(v => v.IsInitialized)*/)
  956. {
  957. nNodes.Add (v);
  958. if (v.LayoutStyle != LayoutStyle.Computed)
  959. {
  960. continue;
  961. }
  962. CollectPos (v.X, v, ref nNodes, ref nEdges);
  963. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  964. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  965. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  966. }
  967. }
  968. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  969. {
  970. switch (dim)
  971. {
  972. case Dim.DimView dv:
  973. // See #2461
  974. //if (!from.InternalSubviews.Contains (dv.Target)) {
  975. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  976. //}
  977. if (dv.Target != this)
  978. {
  979. nEdges.Add ((dv.Target, from));
  980. }
  981. return;
  982. case Dim.DimCombine dc:
  983. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  984. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  985. break;
  986. }
  987. }
  988. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  989. {
  990. switch (pos)
  991. {
  992. case Pos.PosView pv:
  993. // See #2461
  994. //if (!from.InternalSubviews.Contains (pv.Target)) {
  995. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  996. //}
  997. if (pv.Target != this)
  998. {
  999. nEdges.Add ((pv.Target, from));
  1000. }
  1001. return;
  1002. case Pos.PosCombine pc:
  1003. CollectPos (pc._left, from, ref nNodes, ref nEdges);
  1004. CollectPos (pc._right, from, ref nNodes, ref nEdges);
  1005. break;
  1006. }
  1007. }
  1008. // https://en.wikipedia.org/wiki/Topological_sorting
  1009. internal static List<View> TopologicalSort (
  1010. View superView,
  1011. IEnumerable<View> nodes,
  1012. ICollection<(View From, View To)> edges
  1013. )
  1014. {
  1015. List<View> result = new ();
  1016. // Set of all nodes with no incoming edges
  1017. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  1018. while (noEdgeNodes.Any ())
  1019. {
  1020. // remove a node n from S
  1021. View n = noEdgeNodes.First ();
  1022. noEdgeNodes.Remove (n);
  1023. // add n to tail of L
  1024. if (n != superView)
  1025. {
  1026. result.Add (n);
  1027. }
  1028. // for each node m with an edge e from n to m do
  1029. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  1030. {
  1031. View m = e.To;
  1032. // remove edge e from the graph
  1033. edges.Remove (e);
  1034. // if m has no other incoming edges then
  1035. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  1036. {
  1037. // insert m into S
  1038. noEdgeNodes.Add (m);
  1039. }
  1040. }
  1041. }
  1042. if (!edges.Any ())
  1043. {
  1044. return result;
  1045. }
  1046. foreach ((View from, View to) in edges)
  1047. {
  1048. if (from == to)
  1049. {
  1050. // if not yet added to the result, add it and remove from edge
  1051. if (result.Find (v => v == from) is null)
  1052. {
  1053. result.Add (from);
  1054. }
  1055. edges.Remove ((from, to));
  1056. }
  1057. else if (from.SuperView == to.SuperView)
  1058. {
  1059. // if 'from' is not yet added to the result, add it
  1060. if (result.Find (v => v == from) is null)
  1061. {
  1062. result.Add (from);
  1063. }
  1064. // if 'to' is not yet added to the result, add it
  1065. if (result.Find (v => v == to) is null)
  1066. {
  1067. result.Add (to);
  1068. }
  1069. // remove from edge
  1070. edges.Remove ((from, to));
  1071. }
  1072. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  1073. {
  1074. if (ReferenceEquals (from.SuperView, to))
  1075. {
  1076. throw new InvalidOperationException (
  1077. $"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\")."
  1078. );
  1079. }
  1080. throw new InvalidOperationException (
  1081. $"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  1082. );
  1083. }
  1084. }
  1085. // return L (a topologically sorted order)
  1086. return result;
  1087. } // TopologicalSort
  1088. // Diagnostics to highlight when X or Y is read before the view has been initialized
  1089. private Pos VerifyIsInitialized (Pos pos, string member)
  1090. {
  1091. #if DEBUG
  1092. if (pos is not Pos.PosAbsolute && LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1093. {
  1094. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; {member} is indeterminate ({pos}). This is potentially a bug.");
  1095. }
  1096. #endif // DEBUG
  1097. return pos;
  1098. }
  1099. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  1100. private Dim VerifyIsInitialized (Dim dim, string member)
  1101. {
  1102. #if DEBUG
  1103. if (dim is not Dim.DimAbsolute && LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1104. {
  1105. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; {member} is indeterminate: ({dim}). This is potentially a bug.");
  1106. }
  1107. #endif // DEBUG
  1108. return dim;
  1109. }
  1110. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  1111. /// <remarks>
  1112. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  1113. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  1114. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  1115. /// thus should only be used for debugging.
  1116. /// </remarks>
  1117. public bool ValidatePosDim { get; set; }
  1118. }