ViewLayout.cs 49 KB

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