ViewLayout.cs 53 KB

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