ViewLayout.cs 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  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:
  985. case Pos.PosAbsolute:
  986. case Pos.PosFactor:
  987. case Pos.PosFunc:
  988. case Pos.PosView:
  989. default:
  990. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  991. newDimension = Math.Max (
  992. GetNewDimension (dim, newLocation, superviewDimension, autosizeDimension),
  993. 0
  994. );
  995. break;
  996. }
  997. return (newLocation, newDimension);
  998. }
  999. // horizontal/width
  1000. (newX, newW) = GetNewLocationAndDimension (true, superviewContentSize, _x, _width, autosize.Width);
  1001. // vertical/height
  1002. (newY, newH) = GetNewLocationAndDimension (false, superviewContentSize, _y, _height, autosize.Height);
  1003. Rectangle r = new (newX, newY, newW, newH);
  1004. if (Frame != r)
  1005. {
  1006. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  1007. // the view LayoutStyle.Absolute.
  1008. SetFrame (r);
  1009. if (_x is Pos.PosAbsolute)
  1010. {
  1011. _x = Frame.X;
  1012. }
  1013. if (_y is Pos.PosAbsolute)
  1014. {
  1015. _y = Frame.Y;
  1016. }
  1017. if (_width is Dim.DimAbsolute)
  1018. {
  1019. _width = Frame.Width;
  1020. }
  1021. if (_height is Dim.DimAbsolute)
  1022. {
  1023. _height = Frame.Height;
  1024. }
  1025. SetNeedsLayout ();
  1026. SetNeedsDisplay ();
  1027. }
  1028. if (AutoSize)
  1029. {
  1030. if (autosize.Width == 0 || autosize.Height == 0)
  1031. {
  1032. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  1033. // the view LayoutStyle.Absolute.
  1034. SetFrame (_frame with { Size = autosize });
  1035. if (autosize.Width == 0)
  1036. {
  1037. _width = 0;
  1038. }
  1039. if (autosize.Height == 0)
  1040. {
  1041. _height = 0;
  1042. }
  1043. }
  1044. else if (!SetFrameToFitText ())
  1045. {
  1046. SetTextFormatterSize ();
  1047. }
  1048. SetNeedsLayout ();
  1049. SetNeedsDisplay ();
  1050. }
  1051. }
  1052. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1053. {
  1054. // BUGBUG: This should really only work on initialized subviews
  1055. foreach (View v in from.InternalSubviews /*.Where(v => v.IsInitialized)*/)
  1056. {
  1057. nNodes.Add (v);
  1058. if (v.LayoutStyle != LayoutStyle.Computed)
  1059. {
  1060. continue;
  1061. }
  1062. CollectPos (v.X, v, ref nNodes, ref nEdges);
  1063. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  1064. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  1065. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  1066. }
  1067. }
  1068. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1069. {
  1070. switch (dim)
  1071. {
  1072. case Dim.DimView dv:
  1073. // See #2461
  1074. //if (!from.InternalSubviews.Contains (dv.Target)) {
  1075. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  1076. //}
  1077. if (dv.Target != this)
  1078. {
  1079. nEdges.Add ((dv.Target, from));
  1080. }
  1081. return;
  1082. case Dim.DimCombine dc:
  1083. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  1084. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  1085. break;
  1086. }
  1087. }
  1088. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1089. {
  1090. switch (pos)
  1091. {
  1092. case Pos.PosView pv:
  1093. // See #2461
  1094. //if (!from.InternalSubviews.Contains (pv.Target)) {
  1095. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  1096. //}
  1097. if (pv.Target != this)
  1098. {
  1099. nEdges.Add ((pv.Target, from));
  1100. }
  1101. return;
  1102. case Pos.PosCombine pc:
  1103. CollectPos (pc._left, from, ref nNodes, ref nEdges);
  1104. CollectPos (pc._right, from, ref nNodes, ref nEdges);
  1105. break;
  1106. }
  1107. }
  1108. // https://en.wikipedia.org/wiki/Topological_sorting
  1109. internal static List<View> TopologicalSort (
  1110. View superView,
  1111. IEnumerable<View> nodes,
  1112. ICollection<(View From, View To)> edges
  1113. )
  1114. {
  1115. List<View> result = new ();
  1116. // Set of all nodes with no incoming edges
  1117. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  1118. while (noEdgeNodes.Any ())
  1119. {
  1120. // remove a node n from S
  1121. View n = noEdgeNodes.First ();
  1122. noEdgeNodes.Remove (n);
  1123. // add n to tail of L
  1124. if (n != superView)
  1125. {
  1126. result.Add (n);
  1127. }
  1128. // for each node m with an edge e from n to m do
  1129. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  1130. {
  1131. View m = e.To;
  1132. // remove edge e from the graph
  1133. edges.Remove (e);
  1134. // if m has no other incoming edges then
  1135. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  1136. {
  1137. // insert m into S
  1138. noEdgeNodes.Add (m);
  1139. }
  1140. }
  1141. }
  1142. if (!edges.Any ())
  1143. {
  1144. return result;
  1145. }
  1146. foreach ((View from, View to) in edges)
  1147. {
  1148. if (from == to)
  1149. {
  1150. // if not yet added to the result, add it and remove from edge
  1151. if (result.Find (v => v == from) is null)
  1152. {
  1153. result.Add (from);
  1154. }
  1155. edges.Remove ((from, to));
  1156. }
  1157. else if (from.SuperView == to.SuperView)
  1158. {
  1159. // if 'from' is not yet added to the result, add it
  1160. if (result.Find (v => v == from) is null)
  1161. {
  1162. result.Add (from);
  1163. }
  1164. // if 'to' is not yet added to the result, add it
  1165. if (result.Find (v => v == to) is null)
  1166. {
  1167. result.Add (to);
  1168. }
  1169. // remove from edge
  1170. edges.Remove ((from, to));
  1171. }
  1172. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  1173. {
  1174. if (ReferenceEquals (from.SuperView, to))
  1175. {
  1176. throw new InvalidOperationException (
  1177. $"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\")."
  1178. );
  1179. }
  1180. throw new InvalidOperationException (
  1181. $"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  1182. );
  1183. }
  1184. }
  1185. // return L (a topologically sorted order)
  1186. return result;
  1187. } // TopologicalSort
  1188. #region Diagnostics
  1189. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  1190. private Dim VerifyIsInitialized (Dim dim, string member)
  1191. {
  1192. #if DEBUG
  1193. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1194. {
  1195. Debug.WriteLine (
  1196. $"WARNING: \"{this}\" has not been initialized; {member} is indeterminate: {dim}. This is potentially a bug."
  1197. );
  1198. }
  1199. #endif // DEBUG
  1200. return dim;
  1201. }
  1202. // Diagnostics to highlight when X or Y is read before the view has been initialized
  1203. private Pos VerifyIsInitialized (Pos pos, string member)
  1204. {
  1205. #if DEBUG
  1206. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1207. {
  1208. Debug.WriteLine (
  1209. $"WARNING: \"{this}\" has not been initialized; {member} is indeterminate {pos}. This is potentially a bug."
  1210. );
  1211. }
  1212. #endif // DEBUG
  1213. return pos;
  1214. }
  1215. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  1216. /// <remarks>
  1217. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  1218. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  1219. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  1220. /// thus should only be used for debugging.
  1221. /// </remarks>
  1222. public bool ValidatePosDim { get; set; }
  1223. #endregion
  1224. }