2
0

ViewLayout.cs 51 KB

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