ViewLayout.cs 52 KB

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