ViewLayout.cs 58 KB

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