ViewLayout.cs 46 KB

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