ViewLayout.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  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 NStack;
  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="Redraw(Rect)"/> 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. size = Bounds.Size;
  344. if (!AutoSize && !ustring.IsNullOrEmpty (TextFormatter.Text)) {
  345. switch (TextFormatter.IsVerticalDirection (TextDirection)) {
  346. case true:
  347. var colWidth = TextFormatter.GetSumMaxCharWidth (new List<ustring> { TextFormatter.Text }, 0, 1);
  348. // TODO: v2 - This uses frame.Width; it should only use Bounds
  349. if (_frame.Width < colWidth &&
  350. (Width == null ||
  351. (Bounds.Width >= 0 &&
  352. Width is Dim.DimAbsolute &&
  353. Width.Anchor (0) >= 0 &&
  354. Width.Anchor (0) < colWidth))) {
  355. size = new Size (colWidth, Bounds.Height);
  356. return true;
  357. }
  358. break;
  359. default:
  360. if (_frame.Height < 1 &&
  361. (Height == null ||
  362. (Height is Dim.DimAbsolute &&
  363. Height.Anchor (0) == 0))) {
  364. size = new Size (Bounds.Width, 1);
  365. return true;
  366. }
  367. break;
  368. }
  369. }
  370. return false;
  371. }
  372. // BUGBUG - v2 - Should be renamed "SetBoundsToFitFrame"
  373. /// <summary>
  374. /// Sets the size of the View to the minimum width or height required to fit <see cref="Text"/> (see <see cref="GetMinimumBounds(out Size)"/>.
  375. /// </summary>
  376. /// <returns><see langword="true"/> if the size was changed, <see langword="false"/> if <see cref="Text"/>
  377. /// will not fit.</returns>
  378. public bool SetMinWidthHeight ()
  379. {
  380. if (GetMinimumBounds (out Size size)) {
  381. _frame = new Rect (_frame.Location, size);
  382. return true;
  383. }
  384. return false;
  385. }
  386. /// <summary>
  387. /// Called whenever the view needs to be resized. Sets <see cref="Frame"/> and
  388. /// triggers a <see cref="LayoutSubviews()"/> call. ///
  389. /// </summary>
  390. /// <remarks>
  391. /// Can be overridden if the view resize behavior is different than the default.
  392. /// </remarks>
  393. protected virtual void OnResizeNeeded ()
  394. {
  395. var actX = _x is Pos.PosAbsolute ? _x.Anchor (0) : _frame.X;
  396. var actY = _y is Pos.PosAbsolute ? _y.Anchor (0) : _frame.Y;
  397. if (AutoSize) {
  398. //if (TextAlignment == TextAlignment.Justified) {
  399. // throw new InvalidOperationException ("TextAlignment.Justified cannot be used with AutoSize");
  400. //}
  401. var s = GetAutoSize ();
  402. var w = _width is Dim.DimAbsolute && _width.Anchor (0) > s.Width ? _width.Anchor (0) : s.Width;
  403. var h = _height is Dim.DimAbsolute && _height.Anchor (0) > s.Height ? _height.Anchor (0) : s.Height;
  404. _frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
  405. } else {
  406. var w = _width is Dim.DimAbsolute ? _width.Anchor (0) : _frame.Width;
  407. var h = _height is Dim.DimAbsolute ? _height.Anchor (0) : _frame.Height;
  408. // BUGBUG: v2 - ? - If layoutstyle is absolute, this overwrites the current frame h/w with 0. Hmmm...
  409. // This is needed for DimAbsolute values by setting the frame before LayoutSubViews.
  410. _frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
  411. }
  412. //// BUGBUG: I think these calls are redundant or should be moved into just the AutoSize case
  413. if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
  414. SetMinWidthHeight ();
  415. LayoutFrames ();
  416. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  417. SetNeedsLayout ();
  418. SetNeedsDisplay ();
  419. }
  420. }
  421. internal bool LayoutNeeded { get; private set; } = true;
  422. internal void SetNeedsLayout ()
  423. {
  424. if (LayoutNeeded)
  425. return;
  426. LayoutNeeded = true;
  427. if (SuperView == null)
  428. return;
  429. SuperView.SetNeedsLayout ();
  430. foreach (var view in Subviews) {
  431. view.SetNeedsLayout ();
  432. }
  433. TextFormatter.NeedsFormat = true;
  434. }
  435. /// <summary>
  436. /// Removes the <see cref="SetNeedsLayout"/> setting on this view.
  437. /// </summary>
  438. protected void ClearLayoutNeeded ()
  439. {
  440. LayoutNeeded = false;
  441. }
  442. /// <summary>
  443. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  444. /// </summary>
  445. /// <returns>The mapped point.</returns>
  446. /// <param name="x">X screen-coordinate point.</param>
  447. /// <param name="y">Y screen-coordinate point.</param>
  448. public Point ScreenToView (int x, int y)
  449. {
  450. if (SuperView == null) {
  451. return new Point (x - Frame.X, y - _frame.Y);
  452. } else {
  453. var parent = SuperView.ScreenToView (x, y);
  454. return new Point (parent.X - _frame.X, parent.Y - _frame.Y);
  455. }
  456. }
  457. /// <summary>
  458. /// Converts a point from screen-relative coordinates to bounds-relative coordinates.
  459. /// </summary>
  460. /// <returns>The mapped point.</returns>
  461. /// <param name="x">X screen-coordinate point.</param>
  462. /// <param name="y">Y screen-coordinate point.</param>
  463. public Point ScreenToBounds (int x, int y)
  464. {
  465. if (SuperView == null) {
  466. var boundsOffset = GetBoundsOffset ();
  467. return new Point (x - Frame.X + boundsOffset.X, y - Frame.Y + boundsOffset.Y);
  468. } else {
  469. var parent = SuperView.ScreenToView (x, y);
  470. return new Point (parent.X - _frame.X, parent.Y - _frame.Y);
  471. }
  472. }
  473. /// <summary>
  474. /// Converts a view-relative location to a screen-relative location (col,row). The output is optionally clamped to the screen dimensions.
  475. /// </summary>
  476. /// <param name="col">View-relative column.</param>
  477. /// <param name="row">View-relative row.</param>
  478. /// <param name="rcol">Absolute column; screen-relative.</param>
  479. /// <param name="rrow">Absolute row; screen-relative.</param>
  480. /// <param name="clamped">If <see langword="true"/>, <paramref name="rcol"/> and <paramref name="rrow"/> will be clamped to the
  481. /// screen dimensions (they never be negative and will always be less than to <see cref="ConsoleDriver.Cols"/> and
  482. /// <see cref="ConsoleDriver.Rows"/>, respectively.</param>
  483. public virtual void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clamped = true)
  484. {
  485. var boundsOffset = GetBoundsOffset ();
  486. rcol = col + Frame.X + boundsOffset.X;
  487. rrow = row + Frame.Y + boundsOffset.Y;
  488. var super = SuperView;
  489. while (super != null) {
  490. boundsOffset = super.GetBoundsOffset ();
  491. rcol += super.Frame.X + boundsOffset.X;
  492. rrow += super.Frame.Y + boundsOffset.Y;
  493. super = super.SuperView;
  494. }
  495. // The following ensures that the cursor is always in the screen boundaries.
  496. if (clamped) {
  497. rrow = Math.Min (rrow, Driver.Rows - 1);
  498. rcol = Math.Min (rcol, Driver.Cols - 1);
  499. }
  500. }
  501. /// <summary>
  502. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  503. /// </summary>
  504. internal Rect ViewToScreen (Rect region)
  505. {
  506. ViewToScreen (region.X, region.Y, out var x, out var y, clamped: false);
  507. return new Rect (x, y, region.Width, region.Height);
  508. }
  509. /// <summary>
  510. /// Sets the View's <see cref="Frame"/> to the frame-relative coordinates if its container. The
  511. /// container size and location are specified by <paramref name="superviewFrame"/> and are relative to the
  512. /// View's superview.
  513. /// </summary>
  514. /// <param name="superviewFrame">The supserview-relative rectangle describing View's container (nominally the
  515. /// same as <c>this.SuperView.Frame</c>).</param>
  516. internal void SetRelativeLayout (Rect superviewFrame)
  517. {
  518. int newX, newW, newY, newH;
  519. var autosize = Size.Empty;
  520. if (AutoSize) {
  521. // Note this is global to this function and used as such within the local functions defined
  522. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  523. autosize = GetAutoSize ();
  524. }
  525. // Returns the new dimension (width or height) and location (x or y) for the View given
  526. // the superview's Frame.X or Frame.Y
  527. // the superview's width or height
  528. // the current Pos (View.X or View.Y)
  529. // the current Dim (View.Width or View.Height)
  530. (int newLocation, int newDimension) GetNewLocationAndDimension (int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
  531. {
  532. int newDimension, newLocation;
  533. switch (pos) {
  534. case Pos.PosCenter:
  535. if (dim == null) {
  536. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  537. } else {
  538. newDimension = dim.Anchor (superviewDimension);
  539. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  540. }
  541. newLocation = pos.Anchor (superviewDimension - newDimension);
  542. break;
  543. case Pos.PosCombine combine:
  544. int left, right;
  545. (left, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.left, dim, autosizeDimension);
  546. (right, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.right, dim, autosizeDimension);
  547. if (combine.add) {
  548. newLocation = left + right;
  549. } else {
  550. newLocation = left - right;
  551. }
  552. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  553. break;
  554. case Pos.PosAbsolute:
  555. case Pos.PosAnchorEnd:
  556. case Pos.PosFactor:
  557. case Pos.PosFunc:
  558. case Pos.PosView:
  559. default:
  560. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  561. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  562. break;
  563. }
  564. return (newLocation, newDimension);
  565. }
  566. // Recursively calculates the new dimension (width or height) of the given Dim given:
  567. // the current location (x or y)
  568. // the current dimension (width or height)
  569. int CalculateNewDimension (Dim d, int location, int dimension, int autosize)
  570. {
  571. int newDimension;
  572. switch (d) {
  573. case null:
  574. newDimension = AutoSize ? autosize : dimension;
  575. break;
  576. case Dim.DimCombine combine:
  577. int leftNewDim = CalculateNewDimension (combine.left, location, dimension, autosize);
  578. int rightNewDim = CalculateNewDimension (combine.right, location, dimension, autosize);
  579. if (combine.add) {
  580. newDimension = leftNewDim + rightNewDim;
  581. } else {
  582. newDimension = leftNewDim - rightNewDim;
  583. }
  584. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  585. break;
  586. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  587. newDimension = d.Anchor (dimension);
  588. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  589. break;
  590. case Dim.DimFill:
  591. default:
  592. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  593. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  594. break;
  595. }
  596. return newDimension;
  597. }
  598. // horizontal
  599. (newX, newW) = GetNewLocationAndDimension (superviewFrame.X, superviewFrame.Width, _x, _width, autosize.Width);
  600. // vertical
  601. (newY, newH) = GetNewLocationAndDimension (superviewFrame.Y, superviewFrame.Height, _y, _height, autosize.Height);
  602. var r = new Rect (newX, newY, newW, newH);
  603. if (Frame != r) {
  604. Frame = r;
  605. // BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
  606. if (!SetMinWidthHeight ()) {
  607. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  608. }
  609. }
  610. }
  611. /// <summary>
  612. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  613. /// </summary>
  614. /// <remarks>
  615. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  616. /// </remarks>
  617. public event EventHandler<LayoutEventArgs> LayoutStarted;
  618. /// <summary>
  619. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  620. /// </summary>
  621. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  622. {
  623. LayoutStarted?.Invoke (this, args);
  624. }
  625. /// <summary>
  626. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  627. /// </summary>
  628. /// <remarks>
  629. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  630. /// </remarks>
  631. public event EventHandler<LayoutEventArgs> LayoutComplete;
  632. /// <summary>
  633. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  634. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  635. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  636. /// </summary>
  637. public event EventHandler Initialized;
  638. /// <summary>
  639. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  640. /// </summary>
  641. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  642. {
  643. LayoutComplete?.Invoke (this, args);
  644. }
  645. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  646. {
  647. switch (pos) {
  648. case Pos.PosView pv:
  649. // See #2461
  650. //if (!from.InternalSubviews.Contains (pv.Target)) {
  651. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  652. //}
  653. if (pv.Target != this) {
  654. nEdges.Add ((pv.Target, from));
  655. }
  656. return;
  657. case Pos.PosCombine pc:
  658. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  659. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  660. break;
  661. }
  662. }
  663. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  664. {
  665. switch (dim) {
  666. case Dim.DimView dv:
  667. // See #2461
  668. //if (!from.InternalSubviews.Contains (dv.Target)) {
  669. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  670. //}
  671. if (dv.Target != this) {
  672. nEdges.Add ((dv.Target, from));
  673. }
  674. return;
  675. case Dim.DimCombine dc:
  676. CollectDim (dc.left, from, ref nNodes, ref nEdges);
  677. CollectDim (dc.right, from, ref nNodes, ref nEdges);
  678. break;
  679. }
  680. }
  681. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  682. {
  683. foreach (var v in from.InternalSubviews) {
  684. nNodes.Add (v);
  685. if (v._layoutStyle != LayoutStyle.Computed) {
  686. continue;
  687. }
  688. CollectPos (v.X, v, ref nNodes, ref nEdges);
  689. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  690. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  691. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  692. }
  693. }
  694. // https://en.wikipedia.org/wiki/Topological_sorting
  695. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  696. {
  697. var result = new List<View> ();
  698. // Set of all nodes with no incoming edges
  699. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  700. while (noEdgeNodes.Any ()) {
  701. // remove a node n from S
  702. var n = noEdgeNodes.First ();
  703. noEdgeNodes.Remove (n);
  704. // add n to tail of L
  705. if (n != superView)
  706. result.Add (n);
  707. // for each node m with an edge e from n to m do
  708. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  709. var m = e.To;
  710. // remove edge e from the graph
  711. edges.Remove (e);
  712. // if m has no other incoming edges then
  713. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  714. // insert m into S
  715. noEdgeNodes.Add (m);
  716. }
  717. }
  718. }
  719. if (edges.Any ()) {
  720. foreach ((var from, var to) in edges) {
  721. if (from == to) {
  722. // if not yet added to the result, add it and remove from edge
  723. if (result.Find (v => v == from) == null) {
  724. result.Add (from);
  725. }
  726. edges.Remove ((from, to));
  727. } else if (from.SuperView == to.SuperView) {
  728. // if 'from' is not yet added to the result, add it
  729. if (result.Find (v => v == from) == null) {
  730. result.Add (from);
  731. }
  732. // if 'to' is not yet added to the result, add it
  733. if (result.Find (v => v == to) == null) {
  734. result.Add (to);
  735. }
  736. // remove from edge
  737. edges.Remove ((from, to));
  738. } else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to)) {
  739. if (ReferenceEquals (from.SuperView, to)) {
  740. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
  741. } else {
  742. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
  743. }
  744. }
  745. }
  746. }
  747. // return L (a topologically sorted order)
  748. return result;
  749. } // TopologicalSort
  750. /// <summary>
  751. /// Overriden by <see cref="Frame"/> to do nothing, as the <see cref="Frame"/> does not have frames.
  752. /// </summary>
  753. internal virtual void LayoutFrames ()
  754. {
  755. if (Margin == null) return; // CreateFrames() has not been called yet
  756. if (Margin.Frame.Size != Frame.Size) {
  757. Margin._frame = new Rect (Point.Empty, Frame.Size);
  758. Margin.X = 0;
  759. Margin.Y = 0;
  760. Margin.Width = Frame.Size.Width;
  761. Margin.Height = Frame.Size.Height;
  762. Margin.SetNeedsLayout ();
  763. Margin.LayoutSubviews ();
  764. Margin.SetNeedsDisplay ();
  765. }
  766. var border = Margin.Thickness.GetInside (Margin.Frame);
  767. if (border != Border.Frame) {
  768. Border._frame = new Rect (new Point (border.Location.X, border.Location.Y), border.Size);
  769. Border.X = border.Location.X;
  770. Border.Y = border.Location.Y;
  771. Border.Width = border.Size.Width;
  772. Border.Height = border.Size.Height;
  773. Border.SetNeedsLayout ();
  774. Border.LayoutSubviews ();
  775. Border.SetNeedsDisplay ();
  776. }
  777. var padding = Border.Thickness.GetInside (Border.Frame);
  778. if (padding != Padding.Frame) {
  779. Padding._frame = new Rect (new Point (padding.Location.X, padding.Location.Y), padding.Size);
  780. Padding.X = padding.Location.X;
  781. Padding.Y = padding.Location.Y;
  782. Padding.Width = padding.Size.Width;
  783. Padding.Height = padding.Size.Height;
  784. Padding.SetNeedsLayout ();
  785. Padding.LayoutSubviews ();
  786. Padding.SetNeedsDisplay ();
  787. }
  788. }
  789. /// <summary>
  790. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  791. /// response to the container view or terminal resizing.
  792. /// </summary>
  793. /// <remarks>
  794. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  795. /// </remarks>
  796. public virtual void LayoutSubviews ()
  797. {
  798. if (!LayoutNeeded) {
  799. return;
  800. }
  801. LayoutFrames ();
  802. var oldBounds = Bounds;
  803. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  804. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  805. // Sort out the dependencies of the X, Y, Width, Height properties
  806. var nodes = new HashSet<View> ();
  807. var edges = new HashSet<(View, View)> ();
  808. CollectAll (this, ref nodes, ref edges);
  809. var ordered = View.TopologicalSort (SuperView, nodes, edges);
  810. foreach (var v in ordered) {
  811. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  812. }
  813. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  814. // Use LayoutSubview with the Frame of the 'from'
  815. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded && edges.Count > 0) {
  816. foreach ((var from, var to) in edges) {
  817. LayoutSubview (to, from.Frame);
  818. }
  819. }
  820. LayoutNeeded = false;
  821. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  822. }
  823. private void LayoutSubview (View v, Rect contentArea)
  824. {
  825. if (v.LayoutStyle == LayoutStyle.Computed) {
  826. v.SetRelativeLayout (contentArea);
  827. }
  828. v.LayoutSubviews ();
  829. v.LayoutNeeded = false;
  830. }
  831. bool _autoSize;
  832. /// <summary>
  833. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  834. /// within <see cref="Bounds"/>
  835. /// <para>
  836. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If <see langword="true"/> then
  837. /// <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can fit;
  838. /// if <see cref="Text"/> won't fit the view will be resized as needed.
  839. /// </para>
  840. /// <para>
  841. /// In addition, if <see cref="ForceValidatePosDim"/> is <see langword="true"/> the new values of <see cref="Width"/> and
  842. /// <see cref="Height"/> must be of the same types of the existing one to avoid breaking the <see cref="Dim"/> settings.
  843. /// </para>
  844. /// </summary>
  845. public virtual bool AutoSize {
  846. get => _autoSize;
  847. set {
  848. var v = ResizeView (value);
  849. TextFormatter.AutoSize = v;
  850. if (_autoSize != v) {
  851. _autoSize = v;
  852. TextFormatter.NeedsFormat = true;
  853. UpdateTextFormatterText ();
  854. OnResizeNeeded ();
  855. }
  856. }
  857. }
  858. bool ResizeView (bool autoSize)
  859. {
  860. if (!autoSize) {
  861. return false;
  862. }
  863. var aSize = true;
  864. var nBoundsSize = GetAutoSize ();
  865. if (nBoundsSize != Bounds.Size) {
  866. if (ForceValidatePosDim) {
  867. aSize = SetWidthHeight (nBoundsSize);
  868. } else {
  869. Height = nBoundsSize.Height;
  870. Width = nBoundsSize.Width; // = new Rect (Bounds.X, Bounds.Y, nBoundsSize.Width, nBoundsSize.Height);
  871. }
  872. }
  873. // BUGBUG: This call may be redundant
  874. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  875. return aSize;
  876. }
  877. /// <summary>
  878. /// Resizes the View to fit the specified <see cref="Bounds"/> size.
  879. /// </summary>
  880. /// <param name="nBounds"></param>
  881. /// <returns></returns>
  882. bool SetWidthHeight (Size nBounds)
  883. {
  884. var aSize = false;
  885. var canSizeW = TrySetWidth (nBounds.Width - GetHotKeySpecifierLength (), out var rW);
  886. var canSizeH = TrySetHeight (nBounds.Height - GetHotKeySpecifierLength (false), out var rH);
  887. if (canSizeW) {
  888. aSize = true;
  889. _width = rW;
  890. }
  891. if (canSizeH) {
  892. aSize = true;
  893. _height = rH;
  894. }
  895. if (aSize) {
  896. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  897. }
  898. return aSize;
  899. }
  900. /// <summary>
  901. /// Gets the Frame dimensions required to fit <see cref="Text"/> using the text <see cref="Direction"/> specified by the
  902. /// <see cref="TextFormatter"/> property and accounting for any <see cref="HotKeySpecifier"/> characters.
  903. /// </summary>
  904. /// <returns>The <see cref="Size"/> required to fit the text.</returns>
  905. public Size GetAutoSize ()
  906. {
  907. var rect = TextFormatter.CalcRect (Bounds.X, Bounds.Y, TextFormatter.Text, TextFormatter.Direction);
  908. var newWidth = rect.Size.Width - GetHotKeySpecifierLength () + Margin.Thickness.Horizontal + Border.Thickness.Horizontal + Padding.Thickness.Horizontal;
  909. var newHeight = rect.Size.Height - GetHotKeySpecifierLength (false) + Margin.Thickness.Vertical + Border.Thickness.Vertical + Padding.Thickness.Vertical;
  910. return new Size (newWidth, newHeight);
  911. }
  912. bool IsValidAutoSize (out Size autoSize)
  913. {
  914. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  915. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  916. rect.Size.Height - GetHotKeySpecifierLength (false));
  917. return !(ForceValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  918. || _frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  919. || _frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  920. }
  921. bool IsValidAutoSizeWidth (Dim width)
  922. {
  923. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  924. var dimValue = width.Anchor (0);
  925. return !(ForceValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
  926. - GetHotKeySpecifierLength ());
  927. }
  928. bool IsValidAutoSizeHeight (Dim height)
  929. {
  930. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  931. var dimValue = height.Anchor (0);
  932. return !(ForceValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
  933. - GetHotKeySpecifierLength (false));
  934. }
  935. /// <summary>
  936. /// Determines if the View's <see cref="Width"/> can be set to a new value.
  937. /// </summary>
  938. /// <param name="desiredWidth"></param>
  939. /// <param name="resultWidth">Contains the width that would result if <see cref="Width"/> were set to <paramref name="desiredWidth"/>"/> </param>
  940. /// <returns><see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False otherwise.</returns>
  941. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  942. {
  943. var w = desiredWidth;
  944. bool canSetWidth;
  945. switch (Width) {
  946. case Dim.DimCombine _:
  947. case Dim.DimView _:
  948. case Dim.DimFill _:
  949. // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  950. w = Width.Anchor (w);
  951. canSetWidth = !ForceValidatePosDim;
  952. break;
  953. case Dim.DimFactor factor:
  954. // Tries to get the SuperView Width otherwise the view Width.
  955. var sw = SuperView != null ? SuperView.Frame.Width : w;
  956. if (factor.IsFromRemaining ()) {
  957. sw -= Frame.X;
  958. }
  959. w = Width.Anchor (sw);
  960. canSetWidth = !ForceValidatePosDim;
  961. break;
  962. default:
  963. canSetWidth = true;
  964. break;
  965. }
  966. resultWidth = w;
  967. return canSetWidth;
  968. }
  969. /// <summary>
  970. /// Determines if the View's <see cref="Height"/> can be set to a new value.
  971. /// </summary>
  972. /// <param name="desiredHeight"></param>
  973. /// <param name="resultHeight">Contains the width that would result if <see cref="Height"/> were set to <paramref name="desiredHeight"/>"/> </param>
  974. /// <returns><see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False otherwise.</returns>
  975. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  976. {
  977. var h = desiredHeight;
  978. bool canSetHeight;
  979. switch (Height) {
  980. case Dim.DimCombine _:
  981. case Dim.DimView _:
  982. case Dim.DimFill _:
  983. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  984. h = Height.Anchor (h);
  985. canSetHeight = !ForceValidatePosDim;
  986. break;
  987. case Dim.DimFactor factor:
  988. // Tries to get the SuperView height otherwise the view height.
  989. var sh = SuperView != null ? SuperView.Frame.Height : h;
  990. if (factor.IsFromRemaining ()) {
  991. sh -= Frame.Y;
  992. }
  993. h = Height.Anchor (sh);
  994. canSetHeight = !ForceValidatePosDim;
  995. break;
  996. default:
  997. canSetHeight = true;
  998. break;
  999. }
  1000. resultHeight = h;
  1001. return canSetHeight;
  1002. }
  1003. /// <summary>
  1004. /// Finds which view that belong to the <paramref name="start"/> superview at the provided location.
  1005. /// </summary>
  1006. /// <param name="start">The superview where to look for.</param>
  1007. /// <param name="x">The column location in the superview.</param>
  1008. /// <param name="y">The row location in the superview.</param>
  1009. /// <param name="resx">The found view screen relative column location.</param>
  1010. /// <param name="resy">The found view screen relative row location.</param>
  1011. /// <returns>
  1012. /// The view that was found at the <praramref name="x"/> and <praramref name="y"/> coordinates.
  1013. /// <see langword="null"/> if no view was found.
  1014. /// </returns>
  1015. public static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1016. {
  1017. var startFrame = start.Frame;
  1018. if (!startFrame.Contains (x, y)) {
  1019. resx = 0;
  1020. resy = 0;
  1021. return null;
  1022. }
  1023. if (start.InternalSubviews != null) {
  1024. int count = start.InternalSubviews.Count;
  1025. if (count > 0) {
  1026. var boundsOffset = start.GetBoundsOffset ();
  1027. var rx = x - (startFrame.X + boundsOffset.X);
  1028. var ry = y - (startFrame.Y + boundsOffset.Y);
  1029. for (int i = count - 1; i >= 0; i--) {
  1030. View v = start.InternalSubviews [i];
  1031. if (v.Visible && v.Frame.Contains (rx, ry)) {
  1032. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1033. if (deep == null)
  1034. return v;
  1035. return deep;
  1036. }
  1037. }
  1038. }
  1039. }
  1040. resx = x - startFrame.X;
  1041. resy = y - startFrame.Y;
  1042. return start;
  1043. }
  1044. }
  1045. }