ViewLayout.cs 54 KB

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