ViewLayout.cs 58 KB

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