ViewLayout.cs 63 KB

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