ViewLayout.cs 51 KB

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