2
0

ViewLayout.cs 41 KB

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