ViewLayout.cs 53 KB

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