ViewLayout.cs 49 KB

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