ViewLayout.cs 53 KB

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