ViewLayout.cs 49 KB

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