ViewLayout.cs 52 KB

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