ViewLayout.cs 48 KB

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