ViewLayout.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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. TextFormatter.AutoSize = value;
  307. // BUGBUG: This is all a hack until AutoSize is removed
  308. if (value)
  309. {
  310. UpdateTextFormatterText ();
  311. if (IsInitialized)
  312. {
  313. Height = Dim.Auto (Dim.DimAutoStyle.Text);
  314. Width = Dim.Auto (Dim.DimAutoStyle.Text);
  315. }
  316. else
  317. {
  318. _height = Dim.Auto (Dim.DimAutoStyle.Text);
  319. _width = Dim.Auto (Dim.DimAutoStyle.Text);
  320. OnResizeNeeded ();
  321. }
  322. }
  323. else
  324. {
  325. _height = ContentSize.Height;
  326. _width = ContentSize.Width;
  327. OnResizeNeeded ();
  328. }
  329. }
  330. }
  331. ///// <summary>Determines if the View's <see cref="Height"/> can be set to a new value.</summary>
  332. ///// <remarks>TrySetHeight can only be called when AutoSize is true (or being set to true).</remarks>
  333. ///// <param name="desiredHeight"></param>
  334. ///// <param name="resultHeight">
  335. ///// Contains the width that would result if <see cref="Height"/> were set to
  336. ///// <paramref name="desiredHeight"/>"/>
  337. ///// </param>
  338. ///// <returns>
  339. ///// <see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False
  340. ///// otherwise.
  341. ///// </returns>
  342. //internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  343. //{
  344. // int h = desiredHeight;
  345. // bool canSetHeight;
  346. // switch (Height)
  347. // {
  348. // case Dim.DimCombine _:
  349. // case Dim.DimView _:
  350. // case Dim.DimFill _:
  351. // // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  352. // h = Height.Anchor (h);
  353. // canSetHeight = !ValidatePosDim;
  354. // break;
  355. // case Dim.DimFactor factor:
  356. // // Tries to get the SuperView height otherwise the view height.
  357. // int sh = SuperView is { } ? SuperView.Frame.Height : h;
  358. // if (factor.IsFromRemaining ())
  359. // {
  360. // sh -= Frame.Y;
  361. // }
  362. // h = Height.Anchor (sh);
  363. // canSetHeight = !ValidatePosDim;
  364. // break;
  365. // default:
  366. // canSetHeight = true;
  367. // break;
  368. // }
  369. // resultHeight = h;
  370. // return canSetHeight;
  371. //}
  372. ///// <summary>Determines if the View's <see cref="Width"/> can be set to a new value.</summary>
  373. ///// <remarks>TrySetWidth can only be called when AutoSize is true (or being set to true).</remarks>
  374. ///// <param name="desiredWidth"></param>
  375. ///// <param name="resultWidth">
  376. ///// Contains the width that would result if <see cref="Width"/> were set to
  377. ///// <paramref name="desiredWidth"/>"/>
  378. ///// </param>
  379. ///// <returns>
  380. ///// <see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False
  381. ///// otherwise.
  382. ///// </returns>
  383. //internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  384. //{
  385. // int w = desiredWidth;
  386. // bool canSetWidth;
  387. // switch (Width)
  388. // {
  389. // case Dim.DimCombine _:
  390. // case Dim.DimView _:
  391. // case Dim.DimFill _:
  392. // // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  393. // w = Width.Anchor (w);
  394. // canSetWidth = !ValidatePosDim;
  395. // break;
  396. // case Dim.DimFactor factor:
  397. // // Tries to get the SuperView Width otherwise the view Width.
  398. // int sw = SuperView is { } ? SuperView.Frame.Width : w;
  399. // if (factor.IsFromRemaining ())
  400. // {
  401. // sw -= Frame.X;
  402. // }
  403. // w = Width.Anchor (sw);
  404. // canSetWidth = !ValidatePosDim;
  405. // break;
  406. // default:
  407. // canSetWidth = true;
  408. // break;
  409. // }
  410. // resultWidth = w;
  411. // return canSetWidth;
  412. //}
  413. ///// <summary>Resizes the View to fit the specified size. Factors in the HotKey.</summary>
  414. ///// <remarks>ResizeBoundsToFit can only be called when AutoSize is true (or being set to true).</remarks>
  415. ///// <param name="size"></param>
  416. ///// <returns>whether the Viewport was changed or not</returns>
  417. //private bool ResizeViewportToFit (Size size)
  418. //{
  419. // //if (AutoSize == false) {
  420. // // throw new InvalidOperationException ("ResizeViewportToFit can only be called when AutoSize is true");
  421. // //}
  422. // var changed = false;
  423. // bool canSizeW = TrySetWidth (size.Width - GetHotKeySpecifierLength (), out int rW);
  424. // bool canSizeH = TrySetHeight (size.Height - GetHotKeySpecifierLength (false), out int rH);
  425. // if (canSizeW)
  426. // {
  427. // changed = true;
  428. // _width = rW;
  429. // }
  430. // if (canSizeH)
  431. // {
  432. // changed = true;
  433. // _height = rH;
  434. // }
  435. // if (changed)
  436. // {
  437. // Viewport = new (Viewport.X, Viewport.Y, canSizeW ? rW : Viewport.Width, canSizeH ? rH : Viewport.Height);
  438. // }
  439. // return changed;
  440. //}
  441. #endregion AutoSize
  442. #region Layout Engine
  443. /// <summary>
  444. /// Controls how the View's <see cref="Frame"/> is computed during <see cref="LayoutSubviews"/>. If the style is
  445. /// set to <see cref="LayoutStyle.Absolute"/>, LayoutSubviews does not change the <see cref="Frame"/>. If the style is
  446. /// <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using the <see cref="X"/>, <see cref="Y"/>,
  447. /// <see cref="Width"/>, and <see cref="Height"/> properties.
  448. /// </summary>
  449. /// <remarks>
  450. /// <para>
  451. /// Setting this property to <see cref="LayoutStyle.Absolute"/> will cause <see cref="Frame"/> to determine the
  452. /// size and position of the view. <see cref="X"/> and <see cref="Y"/> will be set to <see cref="Dim.DimAbsolute"/>
  453. /// using <see cref="Frame"/>.
  454. /// </para>
  455. /// <para>
  456. /// Setting this property to <see cref="LayoutStyle.Computed"/> will cause the view to use the
  457. /// <see cref="LayoutSubviews"/> method to size and position of the view. If either of the <see cref="X"/> and
  458. /// <see cref="Y"/> properties are `null` they will be set to <see cref="Pos.PosAbsolute"/> using the current value
  459. /// of <see cref="Frame"/>. If either of the <see cref="Width"/> and <see cref="Height"/> properties are `null`
  460. /// they will be set to <see cref="Dim.DimAbsolute"/> using <see cref="Frame"/>.
  461. /// </para>
  462. /// </remarks>
  463. /// <value>The layout style.</value>
  464. public LayoutStyle LayoutStyle
  465. {
  466. get
  467. {
  468. if (_x is Pos.PosAbsolute
  469. && _y is Pos.PosAbsolute
  470. && _width is Dim.DimAbsolute
  471. && _height is Dim.DimAbsolute)
  472. {
  473. return LayoutStyle.Absolute;
  474. }
  475. return LayoutStyle.Computed;
  476. }
  477. }
  478. #endregion Layout Engine
  479. /// <summary>
  480. /// Indicates whether the specified SuperView-relative coordinates are within the View's <see cref="Frame"/>.
  481. /// </summary>
  482. /// <param name="x">SuperView-relative X coordinate.</param>
  483. /// <param name="y">SuperView-relative Y coordinate.</param>
  484. /// <returns><see langword="true"/> if the specified SuperView-relative coordinates are within the View.</returns>
  485. public virtual bool Contains (int x, int y) { return Frame.Contains (x, y); }
  486. #nullable enable
  487. /// <summary>Finds the first Subview of <paramref name="start"/> that is visible at the provided location.</summary>
  488. /// <remarks>
  489. /// <para>
  490. /// Used to determine what view the mouse is over.
  491. /// </para>
  492. /// </remarks>
  493. /// <param name="start">The view to scope the search by.</param>
  494. /// <param name="x"><paramref name="start"/>.SuperView-relative X coordinate.</param>
  495. /// <param name="y"><paramref name="start"/>.SuperView-relative Y coordinate.</param>
  496. /// <returns>
  497. /// The view that was found at the <paramref name="x"/> and <paramref name="y"/> coordinates.
  498. /// <see langword="null"/> if no view was found.
  499. /// </returns>
  500. // CONCURRENCY: This method is not thread-safe. Undefined behavior and likely program crashes are exposed by unsynchronized access to InternalSubviews.
  501. internal static View? FindDeepestView (View? start, int x, int y)
  502. {
  503. while (start is { Visible: true } && start.Contains (x, y))
  504. {
  505. Adornment? found = null;
  506. if (start.Margin.Contains (x, y))
  507. {
  508. found = start.Margin;
  509. }
  510. else if (start.Border.Contains (x, y))
  511. {
  512. found = start.Border;
  513. }
  514. else if (start.Padding.Contains (x, y))
  515. {
  516. found = start.Padding;
  517. }
  518. Point viewportOffset = start.GetViewportOffsetFromFrame ();
  519. if (found is { })
  520. {
  521. start = found;
  522. viewportOffset = found.Parent.Frame.Location;
  523. }
  524. int startOffsetX = x - (start.Frame.X + viewportOffset.X);
  525. int startOffsetY = y - (start.Frame.Y + viewportOffset.Y);
  526. View? subview = null;
  527. for (int i = start.InternalSubviews.Count - 1; i >= 0; i--)
  528. {
  529. if (start.InternalSubviews [i].Visible
  530. && start.InternalSubviews [i].Contains (startOffsetX + start.Viewport.X, startOffsetY + start.Viewport.Y))
  531. {
  532. subview = start.InternalSubviews [i];
  533. x = startOffsetX + start.Viewport.X;
  534. y = startOffsetY + start.Viewport.Y;
  535. // start is the deepest subview under the mouse; stop searching the subviews
  536. break;
  537. }
  538. }
  539. if (subview is null)
  540. {
  541. // No subview was found that's under the mouse, so we're done
  542. return start;
  543. }
  544. // We found a subview of start that's under the mouse, continue...
  545. start = subview;
  546. }
  547. return null;
  548. }
  549. #nullable restore
  550. /// <summary>
  551. /// Gets a new location of the <see cref="View"/> that is within the Viewport of the <paramref name="viewToMove"/>'s
  552. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  553. /// </summary>
  554. /// <remarks>
  555. /// If <paramref name="viewToMove"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  556. /// <see cref="Application.Top"/> the position will be bound by the <see cref="ConsoleDriver.Cols"/> and
  557. /// <see cref="ConsoleDriver.Rows"/>.
  558. /// </remarks>
  559. /// <param name="viewToMove">The View that is to be moved.</param>
  560. /// <param name="targetX">The target x location.</param>
  561. /// <param name="targetY">The target y location.</param>
  562. /// <param name="nx">The new x location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  563. /// <param name="ny">The new y location that will ensure <paramref name="viewToMove"/> will be fully visible.</param>
  564. /// <param name="statusBar">The new top most statusBar</param>
  565. /// <returns>
  566. /// Either <see cref="Application.Top"/> (if <paramref name="viewToMove"/> does not have a Super View) or
  567. /// <paramref name="viewToMove"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  568. /// </returns>
  569. internal static View GetLocationEnsuringFullVisibility (
  570. View viewToMove,
  571. int targetX,
  572. int targetY,
  573. out int nx,
  574. out int ny,
  575. out StatusBar statusBar
  576. )
  577. {
  578. int maxDimension;
  579. View superView;
  580. statusBar = null;
  581. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  582. {
  583. maxDimension = Driver.Cols;
  584. superView = Application.Top;
  585. }
  586. else
  587. {
  588. // Use the SuperView's Viewport, not Frame
  589. maxDimension = viewToMove.SuperView.Viewport.Width;
  590. superView = viewToMove.SuperView;
  591. }
  592. if (superView?.Margin is { } && superView == viewToMove.SuperView)
  593. {
  594. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  595. }
  596. if (viewToMove.Frame.Width <= maxDimension)
  597. {
  598. nx = Math.Max (targetX, 0);
  599. nx = nx + viewToMove.Frame.Width > maxDimension ? Math.Max (maxDimension - viewToMove.Frame.Width, 0) : nx;
  600. if (nx > viewToMove.Frame.X + viewToMove.Frame.Width)
  601. {
  602. nx = Math.Max (viewToMove.Frame.Right, 0);
  603. }
  604. }
  605. else
  606. {
  607. nx = targetX;
  608. }
  609. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  610. var menuVisible = false;
  611. var statusVisible = false;
  612. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  613. {
  614. menuVisible = Application.Top.MenuBar?.Visible == true;
  615. }
  616. else
  617. {
  618. View t = viewToMove.SuperView;
  619. while (t is { } and not Toplevel)
  620. {
  621. t = t.SuperView;
  622. }
  623. if (t is Toplevel toplevel)
  624. {
  625. menuVisible = toplevel.MenuBar?.Visible == true;
  626. }
  627. }
  628. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  629. {
  630. maxDimension = menuVisible ? 1 : 0;
  631. }
  632. else
  633. {
  634. maxDimension = 0;
  635. }
  636. ny = Math.Max (targetY, maxDimension);
  637. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  638. {
  639. statusVisible = Application.Top.StatusBar?.Visible == true;
  640. statusBar = Application.Top.StatusBar;
  641. }
  642. else
  643. {
  644. View t = viewToMove.SuperView;
  645. while (t is { } and not Toplevel)
  646. {
  647. t = t.SuperView;
  648. }
  649. if (t is Toplevel toplevel)
  650. {
  651. statusVisible = toplevel.StatusBar?.Visible == true;
  652. statusBar = toplevel.StatusBar;
  653. }
  654. }
  655. if (viewToMove?.SuperView is null || viewToMove == Application.Top || viewToMove?.SuperView == Application.Top)
  656. {
  657. maxDimension = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  658. }
  659. else
  660. {
  661. maxDimension = statusVisible ? viewToMove.SuperView.Viewport.Height - 1 : viewToMove.SuperView.Viewport.Height;
  662. }
  663. if (superView.Margin is { } && superView == viewToMove.SuperView)
  664. {
  665. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  666. }
  667. ny = Math.Min (ny, maxDimension);
  668. if (viewToMove.Frame.Height <= maxDimension)
  669. {
  670. ny = ny + viewToMove.Frame.Height > maxDimension
  671. ? Math.Max (maxDimension - viewToMove.Frame.Height, menuVisible ? 1 : 0)
  672. : ny;
  673. if (ny > viewToMove.Frame.Y + viewToMove.Frame.Height)
  674. {
  675. ny = Math.Max (viewToMove.Frame.Bottom, 0);
  676. }
  677. }
  678. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  679. return superView;
  680. }
  681. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  682. /// <remarks>
  683. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  684. /// otherwise changed.
  685. /// </remarks>
  686. public event EventHandler<LayoutEventArgs> LayoutComplete;
  687. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  688. /// <remarks>
  689. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  690. /// otherwise changed.
  691. /// </remarks>
  692. public event EventHandler<LayoutEventArgs> LayoutStarted;
  693. /// <summary>
  694. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in response to
  695. /// the container view or terminal resizing.
  696. /// </summary>
  697. /// <remarks>
  698. /// <para>
  699. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  700. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  701. /// </para>
  702. /// <para>Raises the <see cref="LayoutComplete"/> event) before it returns.</para>
  703. /// </remarks>
  704. public virtual void LayoutSubviews ()
  705. {
  706. if (!IsInitialized)
  707. {
  708. Debug.WriteLine ($"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}");
  709. }
  710. if (!LayoutNeeded)
  711. {
  712. return;
  713. }
  714. CheckDimAuto ();
  715. LayoutAdornments ();
  716. OnLayoutStarted (new (ContentSize));
  717. SetTextFormatterSize ();
  718. // Sort out the dependencies of the X, Y, Width, Height properties
  719. HashSet<View> nodes = new ();
  720. HashSet<(View, View)> edges = new ();
  721. CollectAll (this, ref nodes, ref edges);
  722. List<View> ordered = TopologicalSort (SuperView, nodes, edges);
  723. foreach (View v in ordered)
  724. {
  725. // TODO: Move this logic into the Pos/Dim classes
  726. if (v.Width is Dim.DimAuto || v.Height is Dim.DimAuto)
  727. {
  728. // If the view is auto-sized...
  729. Rectangle f = v.Frame;
  730. v._frame = new (v.Frame.X, v.Frame.Y, 0, 0);
  731. LayoutSubview (v, Viewport.Size);
  732. if (v.Frame != f)
  733. {
  734. // The subviews changed; do it again
  735. v.LayoutNeeded = true;
  736. LayoutSubview (v, Viewport.Size);
  737. }
  738. }
  739. else
  740. {
  741. LayoutSubview (v, Viewport.Size);
  742. }
  743. }
  744. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  745. // Use LayoutSubview with the Frame of the 'from'
  746. if (SuperView is { } && GetTopSuperView () is { } && LayoutNeeded && edges.Count > 0)
  747. {
  748. foreach ((View from, View to) in edges)
  749. {
  750. LayoutSubview (to, from.ContentSize);
  751. }
  752. }
  753. LayoutNeeded = false;
  754. OnLayoutComplete (new (ContentSize));
  755. }
  756. // TODO: Move this logic into the Pos/Dim classes
  757. /// <summary>
  758. /// Throws an <see cref="InvalidOperationException"/> if any SubViews are using Dim objects that depend on this
  759. /// Views dimensions.
  760. /// </summary>
  761. /// <exception cref="InvalidOperationException"></exception>
  762. private void CheckDimAuto ()
  763. {
  764. if (!ValidatePosDim || !IsInitialized || (Width is not Dim.DimAuto && Height is not Dim.DimAuto))
  765. {
  766. return;
  767. }
  768. void ThrowInvalid (View view, object checkPosDim, string name)
  769. {
  770. // TODO: Figure out how to make CheckDimAuto deal with PosCombine
  771. object bad = null;
  772. switch (checkPosDim)
  773. {
  774. case Pos pos and not Pos.PosAbsolute and not Pos.PosView and not Pos.PosCombine:
  775. bad = pos;
  776. break;
  777. case Pos pos and Pos.PosCombine:
  778. // Recursively check for not Absolute or not View
  779. ThrowInvalid (view, (pos as Pos.PosCombine)._left, name);
  780. ThrowInvalid (view, (pos as Pos.PosCombine)._right, name);
  781. break;
  782. case Dim dim and not Dim.DimAbsolute and not Dim.DimView and not Dim.DimCombine:
  783. bad = dim;
  784. break;
  785. case Dim dim and Dim.DimCombine:
  786. // Recursively check for not Absolute or not View
  787. ThrowInvalid (view, (dim as Dim.DimCombine)._left, name);
  788. ThrowInvalid (view, (dim as Dim.DimCombine)._right, name);
  789. break;
  790. }
  791. if (bad != null)
  792. {
  793. throw new InvalidOperationException (
  794. @$"{view.GetType ().Name}.{name} = {bad.GetType ().Name} which depends on the SuperView's dimensions and the SuperView uses Dim.Auto.");
  795. }
  796. }
  797. // Verify none of the subviews are using Dim objects that depend on the SuperView's dimensions.
  798. foreach (View view in Subviews)
  799. {
  800. if (Width is Dim.DimAuto { _min: null })
  801. {
  802. ThrowInvalid (view, view.Width, nameof (view.Width));
  803. ThrowInvalid (view, view.X, nameof (view.X));
  804. }
  805. if (Height is Dim.DimAuto { _min: null })
  806. {
  807. ThrowInvalid (view, view.Height, nameof (view.Height));
  808. ThrowInvalid (view, view.Y, nameof (view.Y));
  809. }
  810. }
  811. }
  812. private void LayoutSubview (View v, Size contentSize)
  813. {
  814. v.SetRelativeLayout (contentSize);
  815. v.LayoutSubviews ();
  816. v.LayoutNeeded = false;
  817. }
  818. /// <summary>Indicates that the view does not need to be laid out.</summary>
  819. protected void ClearLayoutNeeded () { LayoutNeeded = false; }
  820. /// <summary>
  821. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views
  822. /// have been laid out.
  823. /// </summary>
  824. internal virtual void OnLayoutComplete (LayoutEventArgs args) { LayoutComplete?.Invoke (this, args); }
  825. /// <summary>
  826. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews
  827. /// have been laid out.
  828. /// </summary>
  829. internal virtual void OnLayoutStarted (LayoutEventArgs args) { LayoutStarted?.Invoke (this, args); }
  830. /// <summary>
  831. /// Called whenever the view needs to be resized. This is called whenever <see cref="Frame"/>,
  832. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or <see cref="View.Height"/> changes.
  833. /// </summary>
  834. /// <remarks>
  835. /// <para>
  836. /// Determines the relative bounds of the <see cref="View"/> and its <see cref="Frame"/>s, and then calls
  837. /// <see cref="SetRelativeLayout(Size)"/> to update the view.
  838. /// </para>
  839. /// </remarks>
  840. internal void OnResizeNeeded ()
  841. {
  842. // TODO: Identify a real-world use-case where this API should be virtual.
  843. // TODO: Until then leave it `internal` and non-virtual
  844. // First try SuperView.Viewport, then Application.Top, then Driver.Viewport.
  845. // Finally, if none of those are valid, use int.MaxValue (for Unit tests).
  846. Size contentSize = SuperView is { IsInitialized: true } ? SuperView.ContentSize :
  847. Application.Top is { } && Application.Top != this && Application.Top.IsInitialized ? Application.Top.ContentSize :
  848. Application.Driver?.Screen.Size ?? new (int.MaxValue, int.MaxValue);
  849. SetTextFormatterSize ();
  850. SetRelativeLayout (contentSize);
  851. if (IsInitialized)
  852. {
  853. LayoutAdornments ();
  854. }
  855. SetNeedsDisplay ();
  856. SetNeedsLayout ();
  857. }
  858. internal bool LayoutNeeded { get; private set; } = true;
  859. /// <summary>
  860. /// Sets the internal <see cref="LayoutNeeded"/> flag for this View and all of it's subviews and it's SuperView.
  861. /// The main loop will call SetRelativeLayout and LayoutSubviews for any view with <see cref="LayoutNeeded"/> set.
  862. /// </summary>
  863. internal void SetNeedsLayout ()
  864. {
  865. if (LayoutNeeded)
  866. {
  867. return;
  868. }
  869. LayoutNeeded = true;
  870. foreach (View view in Subviews)
  871. {
  872. view.SetNeedsLayout ();
  873. }
  874. TextFormatter.NeedsFormat = true;
  875. SuperView?.SetNeedsLayout ();
  876. }
  877. /// <summary>
  878. /// Adjusts <see cref="Frame"/> given the SuperView's ContentSize (nominally the same as
  879. /// <c>this.SuperView.ContentSize</c>)
  880. /// and the position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  881. /// <see cref="Height"/>).
  882. /// </summary>
  883. /// <remarks>
  884. /// <para>
  885. /// If <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, or <see cref="Height"/> are
  886. /// absolute, they will be updated to reflect the new size and position of the view. Otherwise, they
  887. /// are left unchanged.
  888. /// </para>
  889. /// </remarks>
  890. /// <param name="superviewContentSize">
  891. /// The size of the SuperView's content (nominally the same as <c>this.SuperView.ContentSize</c>).
  892. /// </param>
  893. internal void SetRelativeLayout (Size superviewContentSize)
  894. {
  895. Debug.Assert (_x is { });
  896. Debug.Assert (_y is { });
  897. Debug.Assert (_width is { });
  898. Debug.Assert (_height is { });
  899. CheckDimAuto ();
  900. int newX = _x.Calculate (superviewContentSize.Width, _width, this, Dim.Dimension.Width);
  901. int newW = _width.Calculate (newX, superviewContentSize.Width, this, Dim.Dimension.Width);
  902. int newY = _y.Calculate (superviewContentSize.Height, _height, this, Dim.Dimension.Height);
  903. int newH = _height.Calculate (newY, superviewContentSize.Height, this, Dim.Dimension.Height);
  904. Rectangle newFrame = new (newX, newY, newW, newH);
  905. if (Frame != newFrame)
  906. {
  907. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  908. // the view LayoutStyle.Absolute.
  909. SetFrame (newFrame);
  910. if (_x is Pos.PosAbsolute)
  911. {
  912. _x = Frame.X;
  913. }
  914. if (_y is Pos.PosAbsolute)
  915. {
  916. _y = Frame.Y;
  917. }
  918. if (_width is Dim.DimAbsolute)
  919. {
  920. _width = Frame.Width;
  921. }
  922. if (_height is Dim.DimAbsolute)
  923. {
  924. _height = Frame.Height;
  925. }
  926. SetNeedsLayout ();
  927. SetNeedsDisplay ();
  928. }
  929. //if (AutoSize)
  930. //{
  931. // if (autoSize.Width == 0 || autoSize.Height == 0)
  932. // {
  933. // // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  934. // // the view LayoutStyle.Absolute.
  935. // SetFrame (_frame with { Size = autoSize });
  936. // if (autoSize.Width == 0)
  937. // {
  938. // _width = 0;
  939. // }
  940. // if (autoSize.Height == 0)
  941. // {
  942. // _height = 0;
  943. // }
  944. // }
  945. // //else if (!SetFrameToFitText ())
  946. // //{
  947. // // SetTextFormatterSize ();
  948. // //}
  949. // SetNeedsLayout ();
  950. // SetNeedsDisplay ();
  951. //}
  952. }
  953. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  954. {
  955. // BUGBUG: This should really only work on initialized subviews
  956. foreach (View v in from.InternalSubviews /*.Where(v => v.IsInitialized)*/)
  957. {
  958. nNodes.Add (v);
  959. if (v.LayoutStyle != LayoutStyle.Computed)
  960. {
  961. continue;
  962. }
  963. CollectPos (v.X, v, ref nNodes, ref nEdges);
  964. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  965. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  966. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  967. }
  968. }
  969. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  970. {
  971. switch (dim)
  972. {
  973. case Dim.DimView dv:
  974. // See #2461
  975. //if (!from.InternalSubviews.Contains (dv.Target)) {
  976. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  977. //}
  978. if (dv.Target != this)
  979. {
  980. nEdges.Add ((dv.Target, from));
  981. }
  982. return;
  983. case Dim.DimCombine dc:
  984. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  985. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  986. break;
  987. }
  988. }
  989. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  990. {
  991. switch (pos)
  992. {
  993. case Pos.PosView pv:
  994. // See #2461
  995. //if (!from.InternalSubviews.Contains (pv.Target)) {
  996. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  997. //}
  998. if (pv.Target != this)
  999. {
  1000. nEdges.Add ((pv.Target, from));
  1001. }
  1002. return;
  1003. case Pos.PosCombine pc:
  1004. CollectPos (pc._left, from, ref nNodes, ref nEdges);
  1005. CollectPos (pc._right, from, ref nNodes, ref nEdges);
  1006. break;
  1007. }
  1008. }
  1009. // https://en.wikipedia.org/wiki/Topological_sorting
  1010. internal static List<View> TopologicalSort (
  1011. View superView,
  1012. IEnumerable<View> nodes,
  1013. ICollection<(View From, View To)> edges
  1014. )
  1015. {
  1016. List<View> result = new ();
  1017. // Set of all nodes with no incoming edges
  1018. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  1019. while (noEdgeNodes.Any ())
  1020. {
  1021. // remove a node n from S
  1022. View n = noEdgeNodes.First ();
  1023. noEdgeNodes.Remove (n);
  1024. // add n to tail of L
  1025. if (n != superView)
  1026. {
  1027. result.Add (n);
  1028. }
  1029. // for each node m with an edge e from n to m do
  1030. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  1031. {
  1032. View m = e.To;
  1033. // remove edge e from the graph
  1034. edges.Remove (e);
  1035. // if m has no other incoming edges then
  1036. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  1037. {
  1038. // insert m into S
  1039. noEdgeNodes.Add (m);
  1040. }
  1041. }
  1042. }
  1043. if (!edges.Any ())
  1044. {
  1045. return result;
  1046. }
  1047. foreach ((View from, View to) in edges)
  1048. {
  1049. if (from == to)
  1050. {
  1051. // if not yet added to the result, add it and remove from edge
  1052. if (result.Find (v => v == from) is null)
  1053. {
  1054. result.Add (from);
  1055. }
  1056. edges.Remove ((from, to));
  1057. }
  1058. else if (from.SuperView == to.SuperView)
  1059. {
  1060. // if 'from' is not yet added to the result, add it
  1061. if (result.Find (v => v == from) is null)
  1062. {
  1063. result.Add (from);
  1064. }
  1065. // if 'to' is not yet added to the result, add it
  1066. if (result.Find (v => v == to) is null)
  1067. {
  1068. result.Add (to);
  1069. }
  1070. // remove from edge
  1071. edges.Remove ((from, to));
  1072. }
  1073. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  1074. {
  1075. if (ReferenceEquals (from.SuperView, to))
  1076. {
  1077. throw new InvalidOperationException (
  1078. $"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\")."
  1079. );
  1080. }
  1081. throw new InvalidOperationException (
  1082. $"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  1083. );
  1084. }
  1085. }
  1086. // return L (a topologically sorted order)
  1087. return result;
  1088. } // TopologicalSort
  1089. // Diagnostics to highlight when X or Y is read before the view has been initialized
  1090. private Pos VerifyIsInitialized (Pos pos, string member)
  1091. {
  1092. #if DEBUG
  1093. if (pos is not Pos.PosAbsolute && LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1094. {
  1095. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; {member} is indeterminate ({pos}). This is potentially a bug.");
  1096. }
  1097. #endif // DEBUG
  1098. return pos;
  1099. }
  1100. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  1101. private Dim VerifyIsInitialized (Dim dim, string member)
  1102. {
  1103. #if DEBUG
  1104. if (dim is not Dim.DimAbsolute && LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1105. {
  1106. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; {member} is indeterminate: ({dim}). This is potentially a bug.");
  1107. }
  1108. #endif // DEBUG
  1109. return dim;
  1110. }
  1111. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  1112. /// <remarks>
  1113. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  1114. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  1115. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  1116. /// thus should only be used for debugging.
  1117. /// </remarks>
  1118. public bool ValidatePosDim { get; set; }
  1119. }