ViewLayout.cs 65 KB

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