ViewLayout.cs 41 KB

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