2
0

ViewLayout.cs 48 KB

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