ViewLayout.cs 63 KB

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