ViewLayout.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. if (Equals (_x, value))
  150. {
  151. return;
  152. }
  153. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  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. }