ViewLayout.cs 51 KB

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