ViewLayout.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. using System.Diagnostics;
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// <para>Indicates the LayoutStyle for the <see cref="View"/>.</para>
  5. /// <para>
  6. /// If Absolute, the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  7. /// <see cref="View.Height"/> objects are all absolute values and are not relative. The position and size of the
  8. /// view is described by <see cref="View.Frame"/>.
  9. /// </para>
  10. /// <para>
  11. /// If Computed, one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  12. /// <see cref="View.Height"/> objects are relative to the <see cref="View.SuperView"/> and are computed at layout
  13. /// time.
  14. /// </para>
  15. /// </summary>
  16. public enum LayoutStyle
  17. {
  18. /// <summary>
  19. /// Indicates the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and
  20. /// <see cref="View.Height"/> objects are all absolute values and are not relative. The position and size of the view
  21. /// is described by <see cref="View.Frame"/>.
  22. /// </summary>
  23. Absolute,
  24. /// <summary>
  25. /// Indicates one or more of the <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or
  26. /// <see cref="View.Height"/> objects are relative to the <see cref="View.SuperView"/> and are computed at layout time.
  27. /// The position and size of the view will be computed based on these objects at layout time. <see cref="View.Frame"/>
  28. /// will provide the absolute computed values.
  29. /// </summary>
  30. Computed
  31. }
  32. public partial class View
  33. {
  34. #region Frame
  35. private Rectangle _frame;
  36. /// <summary>Gets or sets the absolute location and dimension of the view.</summary>
  37. /// <value>
  38. /// The rectangle describing absolute location and dimension of the view, in coordinates relative to the
  39. /// <see cref="SuperView"/>'s <see cref="Bounds"/>.
  40. /// </value>
  41. /// <remarks>
  42. /// <para>Frame is relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.</para>
  43. /// <para>
  44. /// Setting Frame will set <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> to the
  45. /// values of the corresponding properties of the <paramref name="value"/> parameter.
  46. /// </para>
  47. /// <para>This causes <see cref="LayoutStyle"/> to be <see cref="LayoutStyle.Absolute"/>.</para>
  48. /// <para>
  49. /// Altering the Frame will eventually (when the view hierarchy is next laid out via see
  50. /// cref="LayoutSubviews"/>) cause <see cref="LayoutSubview(View, Rectangle)"/> and
  51. /// <see cref="OnDrawContent(Rectangle)"/>
  52. /// methods to be called.
  53. /// </para>
  54. /// </remarks>
  55. public Rectangle Frame
  56. {
  57. get => _frame;
  58. set
  59. {
  60. _frame = value with { Width = Math.Max (value.Width, 0), Height = Math.Max (value.Height, 0) };
  61. // If Frame gets set, by definition, the View is now LayoutStyle.Absolute, so
  62. // set all Pos/Dim to Absolute values.
  63. _x = _frame.X;
  64. _y = _frame.Y;
  65. _width = _frame.Width;
  66. _height = _frame.Height;
  67. // TODO: Figure out if the below can be optimized.
  68. if (IsInitialized /*|| LayoutStyle == LayoutStyle.Absolute*/)
  69. {
  70. LayoutAdornments ();
  71. SetTextFormatterSize ();
  72. SetNeedsLayout ();
  73. SetNeedsDisplay ();
  74. }
  75. }
  76. }
  77. /// <summary>Gets the <see cref="Frame"/> with a screen-relative location.</summary>
  78. /// <returns>The location and size of the view in screen-relative coordinates.</returns>
  79. public virtual Rectangle FrameToScreen ()
  80. {
  81. Rectangle ret = Frame;
  82. View super = SuperView;
  83. while (super is { })
  84. {
  85. Point boundsOffset = super.GetBoundsOffset ();
  86. if (super is Adornment adornment)
  87. {
  88. // Adornments don't have SuperViews; use Adornment.FrameToScreen override
  89. ret = adornment.FrameToScreen ();
  90. ret.Offset (Frame.X, Frame.Y);
  91. boundsOffset = GetBoundsOffset ();
  92. //ret.Offset(-boundsOffset.X, -boundsOffset.Y);
  93. return ret;
  94. }
  95. ret.X += super.Frame.X + boundsOffset.X;
  96. ret.Y += super.Frame.Y + boundsOffset.Y;
  97. super = super.SuperView;
  98. }
  99. return ret;
  100. }
  101. /// <summary>
  102. /// Converts a screen-relative coordinate to a Frame-relative coordinate. Frame-relative means relative to the
  103. /// View's <see cref="SuperView"/>'s <see cref="Bounds"/>.
  104. /// </summary>
  105. /// <returns>The coordinate relative to the <see cref="SuperView"/>'s <see cref="Bounds"/>.</returns>
  106. /// <param name="x">Screen-relative column.</param>
  107. /// <param name="y">Screen-relative row.</param>
  108. public virtual Point ScreenToFrame (int x, int y)
  109. {
  110. Point superViewBoundsOffset = SuperView?.GetBoundsOffset () ?? Point.Empty;
  111. var ret = new Point (x - Frame.X - superViewBoundsOffset.X, y - Frame.Y - superViewBoundsOffset.Y);
  112. if (SuperView is { })
  113. {
  114. Point superFrame = SuperView.ScreenToFrame (x - superViewBoundsOffset.X, y - superViewBoundsOffset.Y);
  115. ret = new (superFrame.X - Frame.X, superFrame.Y - Frame.Y);
  116. }
  117. return ret;
  118. }
  119. private Pos _x = Pos.At (0);
  120. /// <summary>Gets or sets the X position for the view (the column).</summary>
  121. /// <value>The <see cref="Pos"/> object representing the X position.</value>
  122. /// <remarks>
  123. /// <para>
  124. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  125. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rectangle)"/> has been
  126. /// called.
  127. /// </para>
  128. /// <para>
  129. /// Changing this property will eventually (when the view is next drawn) cause the
  130. /// <see cref="LayoutSubview(View, Rectangle)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  131. /// </para>
  132. /// <para>
  133. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  134. /// <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  135. /// </para>
  136. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  137. /// </remarks>
  138. public Pos X
  139. {
  140. get => VerifyIsInitialized (_x, nameof (X));
  141. set
  142. {
  143. _x = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (X)} cannot be null");
  144. OnResizeNeeded ();
  145. }
  146. }
  147. private Pos _y = Pos.At (0);
  148. /// <summary>Gets or sets the Y position for the view (the row).</summary>
  149. /// <value>The <see cref="Pos"/> object representing the Y position.</value>
  150. /// <remarks>
  151. /// <para>
  152. /// If set to a relative value (e.g. <see cref="Pos.Center"/>) the value is indeterminate until the view has been
  153. /// initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rectangle)"/> has been
  154. /// called.
  155. /// </para>
  156. /// <para>
  157. /// Changing this property will eventually (when the view is next drawn) cause the
  158. /// <see cref="LayoutSubview(View, Rectangle)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  159. /// </para>
  160. /// <para>
  161. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  162. /// <see cref="Pos.PosAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  163. /// </para>
  164. /// <para>The default value is <c>Pos.At (0)</c>.</para>
  165. /// </remarks>
  166. public Pos Y
  167. {
  168. get => VerifyIsInitialized (_y, nameof (Y));
  169. set
  170. {
  171. _y = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Y)} cannot be null");
  172. OnResizeNeeded ();
  173. }
  174. }
  175. private Dim _height = Dim.Sized (0);
  176. /// <summary>Gets or sets the height dimension of the view.</summary>
  177. /// <value>The <see cref="Dim"/> object representing the height of the view (the number of rows).</value>
  178. /// <remarks>
  179. /// <para>
  180. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the view has
  181. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rectangle)"/> has been
  182. /// called.
  183. /// </para>
  184. /// <para>
  185. /// Changing this property will eventually (when the view is next drawn) cause the
  186. /// <see cref="LayoutSubview(View, Rectangle)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  187. /// </para>
  188. /// <para>
  189. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  190. /// <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  191. /// </para>
  192. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  193. /// </remarks>
  194. public Dim Height
  195. {
  196. get => VerifyIsInitialized (_height, nameof (Height));
  197. set
  198. {
  199. _height = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Height)} cannot be null");
  200. if (AutoSize)
  201. {
  202. throw new InvalidOperationException (@$"Must set AutoSize to false before setting {nameof (Height)}.");
  203. }
  204. //if (ValidatePosDim) {
  205. bool isValidNewAutoSize = AutoSize && IsValidAutoSizeHeight (_height);
  206. if (IsAdded && AutoSize && !isValidNewAutoSize)
  207. {
  208. throw new InvalidOperationException (
  209. @$"Must set AutoSize to false before setting the {nameof (Height)}."
  210. );
  211. }
  212. //}
  213. OnResizeNeeded ();
  214. }
  215. }
  216. private Dim _width = Dim.Sized (0);
  217. /// <summary>Gets or sets the width dimension of the view.</summary>
  218. /// <value>The <see cref="Dim"/> object representing the width of the view (the number of columns).</value>
  219. /// <remarks>
  220. /// <para>
  221. /// If set to a relative value (e.g. <see cref="Dim.Fill(int)"/>) the value is indeterminate until the view has
  222. /// been initialized ( <see cref="IsInitialized"/> is true) and <see cref="SetRelativeLayout(Rectangle)"/> has been
  223. /// called.
  224. /// </para>
  225. /// <para>
  226. /// Changing this property will eventually (when the view is next drawn) cause the
  227. /// <see cref="LayoutSubview(View, Rectangle)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  228. /// </para>
  229. /// <para>
  230. /// Changing this property will cause <see cref="Frame"/> to be updated. If the new value is not of type
  231. /// <see cref="Dim.DimAbsolute"/> the <see cref="LayoutStyle"/> will change to <see cref="LayoutStyle.Computed"/>.
  232. /// </para>
  233. /// <para>The default value is <c>Dim.Sized (0)</c>.</para>
  234. /// </remarks>
  235. public Dim Width
  236. {
  237. get => VerifyIsInitialized (_width, nameof (Width));
  238. set
  239. {
  240. _width = value ?? throw new ArgumentNullException (nameof (value), @$"{nameof (Width)} cannot be null");
  241. if (AutoSize)
  242. {
  243. throw new InvalidOperationException (@$"Must set AutoSize to false before setting {nameof (Width)}.");
  244. }
  245. bool isValidNewAutoSize = AutoSize && IsValidAutoSizeWidth (_width);
  246. if (IsAdded && AutoSize && !isValidNewAutoSize)
  247. {
  248. throw new InvalidOperationException (@$"Must set AutoSize to false before setting {nameof (Width)}.");
  249. }
  250. OnResizeNeeded ();
  251. }
  252. }
  253. #endregion Frame
  254. #region Bounds
  255. /// <summary>
  256. /// The bounds represent the View-relative rectangle used for this view; the area inside of the view where
  257. /// subviews and content are presented.
  258. /// </summary>
  259. /// <value>The rectangle describing the location and size of the area where the views' subviews and content are drawn.</value>
  260. /// <remarks>
  261. /// <para>
  262. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/> the value of Bounds is indeterminate until
  263. /// the view has been initialized ( <see cref="IsInitialized"/> is true) and <see cref="LayoutSubviews"/> has been
  264. /// called.
  265. /// </para>
  266. /// <para>
  267. /// Updates to the Bounds updates <see cref="Frame"/>, and has the same effect as updating the
  268. /// <see cref="Frame"/>.
  269. /// </para>
  270. /// <para>
  271. /// Altering the Bounds will eventually (when the view is next laid out) cause the
  272. /// <see cref="LayoutSubview(View, Rectangle)"/> and <see cref="OnDrawContent(Rectangle)"/> methods to be called.
  273. /// </para>
  274. /// <para>
  275. /// Because <see cref="Bounds"/> coordinates are relative to the upper-left corner of the <see cref="View"/>, the
  276. /// coordinates of the upper-left corner of the rectangle returned by this property are (0,0). Use this property to
  277. /// obtain the size of the area of the view for tasks such as drawing the view's contents.
  278. /// </para>
  279. /// </remarks>
  280. public virtual Rectangle Bounds
  281. {
  282. get
  283. {
  284. #if DEBUG
  285. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  286. {
  287. Debug.WriteLine (
  288. $"WARNING: Bounds is being accessed before the View has been initialized. This is likely a bug in {this}"
  289. );
  290. }
  291. #endif // DEBUG
  292. if (Margin is null || Border is null || Padding is null)
  293. {
  294. return Rectangle.Empty with { Size = Frame.Size };
  295. }
  296. Thickness totalThickness = GetAdornmentsThickness ();
  297. int width = Math.Max (0, Frame.Size.Width - totalThickness.Horizontal);
  298. int height = Math.Max (0, Frame.Size.Height - totalThickness.Vertical);
  299. return Rectangle.Empty with { Size = new (width, height) };
  300. }
  301. set
  302. {
  303. // TODO: Should we enforce Bounds.X/Y == 0? The code currently ignores value.X/Y which is
  304. // TODO: correct behavior, but is silent. Perhaps an exception?
  305. #if DEBUG
  306. if (value.Location != Point.Empty)
  307. {
  308. Debug.WriteLine (
  309. $"WARNING: Bounds.Location must always be 0,0. Location ({value.Location}) is ignored. {this}"
  310. );
  311. }
  312. #endif // DEBUG
  313. Thickness totalThickness = GetAdornmentsThickness ();
  314. Frame = Frame with
  315. {
  316. Size = new (value.Size.Width + totalThickness.Horizontal, value.Size.Height + totalThickness.Vertical)
  317. };
  318. }
  319. }
  320. /// <summary>Converts a <see cref="Bounds"/>-relative rectangle to a screen-relative rectangle.</summary>
  321. public Rectangle BoundsToScreen (in Rectangle bounds)
  322. {
  323. // Translate bounds to Frame (our SuperView's Bounds-relative coordinates)
  324. Point boundsOffset = GetBoundsOffset ();
  325. Rectangle screen = FrameToScreen ();
  326. screen.Offset (boundsOffset.X + bounds.X, boundsOffset.Y + bounds.Y);
  327. return new (screen.Location, bounds.Size);
  328. }
  329. /// <summary>Converts a screen-relative coordinate to a bounds-relative coordinate.</summary>
  330. /// <returns>The coordinate relative to this view's <see cref="Bounds"/>.</returns>
  331. /// <param name="x">Screen-relative column.</param>
  332. /// <param name="y">Screen-relative row.</param>
  333. public Point ScreenToBounds (int x, int y)
  334. {
  335. Point screen = ScreenToFrame (x, y);
  336. Point boundsOffset = GetBoundsOffset ();
  337. return new (screen.X - boundsOffset.X, screen.Y - boundsOffset.Y);
  338. }
  339. /// <summary>
  340. /// Helper to get the X and Y offset of the Bounds from the Frame. This is the sum of the Left and Top properties
  341. /// of <see cref="Margin"/>, <see cref="Border"/> and <see cref="Padding"/>.
  342. /// </summary>
  343. public virtual Point GetBoundsOffset ()
  344. {
  345. if (Padding is null)
  346. {
  347. return Point.Empty;
  348. }
  349. return Padding.Thickness.GetInside (Padding.Frame).Location;
  350. }
  351. #endregion Bounds
  352. #region Adornments
  353. private void CreateAdornments ()
  354. {
  355. Margin = CreateAdornment (typeof (Margin)) as Margin;
  356. Border = CreateAdornment (typeof (Border)) as Border;
  357. Padding = CreateAdornment (typeof (Padding)) as Padding;
  358. }
  359. // TODO: Move this to Adornment as a static factory method
  360. /// <summary>
  361. /// This internal method is overridden by Adornment to do nothing to prevent recursion during View construction.
  362. /// And, because Adornments don't have Adornments. It's internal to support unit tests.
  363. /// </summary>
  364. /// <param name="adornmentType"></param>
  365. /// <exception cref="ArgumentNullException"></exception>
  366. /// <exception cref="ArgumentException"></exception>
  367. internal virtual Adornment CreateAdornment (Type adornmentType)
  368. {
  369. void ThicknessChangedHandler (object sender, EventArgs e)
  370. {
  371. if (IsInitialized)
  372. {
  373. LayoutAdornments ();
  374. }
  375. SetNeedsLayout ();
  376. SetNeedsDisplay ();
  377. }
  378. Adornment adornment;
  379. adornment = Activator.CreateInstance (adornmentType, this) as Adornment;
  380. adornment.ThicknessChanged += ThicknessChangedHandler;
  381. return adornment;
  382. }
  383. private void BeginInitAdornments ()
  384. {
  385. Margin?.BeginInit ();
  386. Border?.BeginInit ();
  387. Padding?.BeginInit ();
  388. }
  389. private void EndInitAdornments ()
  390. {
  391. Margin?.EndInit ();
  392. Border?.EndInit ();
  393. Padding?.EndInit ();
  394. }
  395. private void DisposeAdornments ()
  396. {
  397. Margin?.Dispose ();
  398. Margin = null;
  399. Border?.Dispose ();
  400. Border = null;
  401. Padding?.Dispose ();
  402. Padding = null;
  403. }
  404. /// <summary>
  405. /// The <see cref="Adornment"/> that enables separation of a View from other SubViews of the same
  406. /// SuperView. The margin offsets the <see cref="Bounds"/> from the <see cref="Frame"/>.
  407. /// </summary>
  408. /// <remarks>
  409. /// <para>
  410. /// The adornments (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the
  411. /// View's content and are not clipped by the View's Clip Area.
  412. /// </para>
  413. /// <para>
  414. /// Changing the size of an adornment (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>) will
  415. /// change the size of <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout of the
  416. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  417. /// </para>
  418. /// </remarks>
  419. public Margin Margin { get; private set; }
  420. /// <summary>
  421. /// The <see cref="Adornment"/> that offsets the <see cref="Bounds"/> from the <see cref="Margin"/>.
  422. /// The Border provides the space for a visual border (drawn using
  423. /// line-drawing glyphs) and the Title. The Border expands inward; in other words if `Border.Thickness.Top == 2` the
  424. /// border and title will take up the first row and the second row will be filled with spaces.
  425. /// </summary>
  426. /// <remarks>
  427. /// <para><see cref="BorderStyle"/> provides a simple helper for turning a simple border frame on or off.</para>
  428. /// <para>
  429. /// The adornments (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the
  430. /// View's content and are not clipped by the View's Clip Area.
  431. /// </para>
  432. /// <para>
  433. /// Changing the size of a frame (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>) will
  434. /// change the size of the <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout of the
  435. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  436. /// </para>
  437. /// </remarks>
  438. public Border Border { get; private set; }
  439. /// <summary>Gets or sets whether the view has a one row/col thick border.</summary>
  440. /// <remarks>
  441. /// <para>
  442. /// This is a helper for manipulating the view's <see cref="Border"/>. Setting this property to any value other
  443. /// than <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s
  444. /// <see cref="Adornment.Thickness"/> to `1` and <see cref="BorderStyle"/> to the value.
  445. /// </para>
  446. /// <para>
  447. /// Setting this property to <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s
  448. /// <see cref="Adornment.Thickness"/> to `0` and <see cref="BorderStyle"/> to <see cref="LineStyle.None"/>.
  449. /// </para>
  450. /// <para>For more advanced customization of the view's border, manipulate see <see cref="Border"/> directly.</para>
  451. /// </remarks>
  452. public LineStyle BorderStyle
  453. {
  454. get => Border?.LineStyle ?? LineStyle.Single;
  455. set
  456. {
  457. if (Border is null)
  458. {
  459. return;
  460. }
  461. if (value != LineStyle.None)
  462. {
  463. Border.Thickness = new (1);
  464. }
  465. else
  466. {
  467. Border.Thickness = new (0);
  468. }
  469. Border.LineStyle = value;
  470. LayoutAdornments ();
  471. SetNeedsLayout ();
  472. }
  473. }
  474. /// <summary>
  475. /// The <see cref="Adornment"/> inside of the view that offsets the <see cref="Bounds"/>
  476. /// from the <see cref="Border"/>.
  477. /// </summary>
  478. /// <remarks>
  479. /// <para>
  480. /// The adornments (<see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>) are not part of the
  481. /// View's content and are not clipped by the View's Clip Area.
  482. /// </para>
  483. /// <para>
  484. /// Changing the size of a frame (<see cref="Margin"/>, <see cref="Border"/>, or <see cref="Padding"/>) will
  485. /// change the size of the <see cref="Frame"/> and trigger <see cref="LayoutSubviews"/> to update the layout of the
  486. /// <see cref="SuperView"/> and its <see cref="Subviews"/>.
  487. /// </para>
  488. /// </remarks>
  489. public Padding Padding { get; private set; }
  490. /// <summary>
  491. /// <para>Gets the thickness describing the sum of the Adornments' thicknesses.</para>
  492. /// </summary>
  493. /// <returns>A thickness that describes the sum of the Adornments' thicknesses.</returns>
  494. public Thickness GetAdornmentsThickness () { return Margin.Thickness + Border.Thickness + Padding.Thickness; }
  495. /// <summary>Overriden by <see cref="Adornment"/> to do nothing, as the <see cref="Adornment"/> does not have adornments.</summary>
  496. internal virtual void LayoutAdornments ()
  497. {
  498. if (Margin is null)
  499. {
  500. return; // CreateAdornments () has not been called yet
  501. }
  502. if (Margin.Frame.Size != Frame.Size)
  503. {
  504. Margin._frame = Rectangle.Empty with { Size = Frame.Size };
  505. Margin.X = 0;
  506. Margin.Y = 0;
  507. Margin.Width = Frame.Size.Width;
  508. Margin.Height = Frame.Size.Height;
  509. }
  510. Margin.SetNeedsLayout ();
  511. Margin.SetNeedsDisplay ();
  512. if (IsInitialized)
  513. {
  514. Margin.LayoutSubviews ();
  515. }
  516. Rectangle border = Margin.Thickness.GetInside (Margin.Frame);
  517. if (border != Border.Frame)
  518. {
  519. Border._frame = border;
  520. Border.X = border.Location.X;
  521. Border.Y = border.Location.Y;
  522. Border.Width = border.Size.Width;
  523. Border.Height = border.Size.Height;
  524. }
  525. Border.SetNeedsLayout ();
  526. Border.SetNeedsDisplay ();
  527. if (IsInitialized)
  528. {
  529. Border.LayoutSubviews ();
  530. }
  531. Rectangle padding = Border.Thickness.GetInside (Border.Frame);
  532. if (padding != Padding.Frame)
  533. {
  534. Padding._frame = padding;
  535. Padding.X = padding.Location.X;
  536. Padding.Y = padding.Location.Y;
  537. Padding.Width = padding.Size.Width;
  538. Padding.Height = padding.Size.Height;
  539. }
  540. Padding.SetNeedsLayout ();
  541. Padding.SetNeedsDisplay ();
  542. if (IsInitialized)
  543. {
  544. Padding.LayoutSubviews ();
  545. }
  546. }
  547. #endregion Adornments
  548. #region AutoSize
  549. private bool _autoSize;
  550. /// <summary>
  551. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  552. /// within <see cref="Bounds"/>.
  553. /// <para>
  554. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If
  555. /// <see langword="true"/> then <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can
  556. /// fit; if <see cref="Text"/> won't fit the view will be resized as needed.
  557. /// </para>
  558. /// <para>
  559. /// If <see cref="AutoSize"/> is set to <see langword="true"/> then <see cref="Width"/> and <see cref="Height"/>
  560. /// will be changed to <see cref="Dim.DimAbsolute"/> if they are not already.
  561. /// </para>
  562. /// <para>
  563. /// If <see cref="AutoSize"/> is set to <see langword="false"/> then <see cref="Width"/> and <see cref="Height"/>
  564. /// will left unchanged.
  565. /// </para>
  566. /// </summary>
  567. public virtual bool AutoSize
  568. {
  569. get => _autoSize;
  570. set
  571. {
  572. if (Width != Dim.Sized (0) && Height != Dim.Sized (0))
  573. {
  574. Debug.WriteLine (
  575. $@"WARNING: {GetType ().Name} - Setting {nameof (AutoSize)} invalidates {nameof (Width)} and {nameof (Height)}."
  576. );
  577. }
  578. bool v = ResizeView (value);
  579. TextFormatter.AutoSize = v;
  580. if (_autoSize != v)
  581. {
  582. _autoSize = v;
  583. TextFormatter.NeedsFormat = true;
  584. UpdateTextFormatterText ();
  585. OnResizeNeeded ();
  586. }
  587. }
  588. }
  589. /// <summary>If <paramref name="autoSize"/> is true, resizes the view.</summary>
  590. /// <param name="autoSize"></param>
  591. /// <returns></returns>
  592. private bool ResizeView (bool autoSize)
  593. {
  594. if (!autoSize)
  595. {
  596. return false;
  597. }
  598. var boundsChanged = true;
  599. Size newFrameSize = GetAutoSize ();
  600. if (IsInitialized && newFrameSize != Frame.Size)
  601. {
  602. if (ValidatePosDim)
  603. {
  604. // BUGBUG: This ain't right, obviously. We need to figure out how to handle this.
  605. boundsChanged = ResizeBoundsToFit (newFrameSize);
  606. }
  607. else
  608. {
  609. Height = newFrameSize.Height;
  610. Width = newFrameSize.Width;
  611. }
  612. }
  613. return boundsChanged;
  614. }
  615. /// <summary>Determines if the View's <see cref="Height"/> can be set to a new value.</summary>
  616. /// <remarks>TrySetHeight can only be called when AutoSize is true (or being set to true).</remarks>
  617. /// <param name="desiredHeight"></param>
  618. /// <param name="resultHeight">
  619. /// Contains the width that would result if <see cref="Height"/> were set to
  620. /// <paramref name="desiredHeight"/>"/>
  621. /// </param>
  622. /// <returns>
  623. /// <see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False
  624. /// otherwise.
  625. /// </returns>
  626. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  627. {
  628. int h = desiredHeight;
  629. bool canSetHeight;
  630. switch (Height)
  631. {
  632. case Dim.DimCombine _:
  633. case Dim.DimView _:
  634. case Dim.DimFill _:
  635. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  636. h = Height.Anchor (h);
  637. canSetHeight = !ValidatePosDim;
  638. break;
  639. case Dim.DimFactor factor:
  640. // Tries to get the SuperView height otherwise the view height.
  641. int sh = SuperView is { } ? SuperView.Frame.Height : h;
  642. if (factor.IsFromRemaining ())
  643. {
  644. sh -= Frame.Y;
  645. }
  646. h = Height.Anchor (sh);
  647. canSetHeight = !ValidatePosDim;
  648. break;
  649. default:
  650. canSetHeight = true;
  651. break;
  652. }
  653. resultHeight = h;
  654. return canSetHeight;
  655. }
  656. /// <summary>Determines if the View's <see cref="Width"/> can be set to a new value.</summary>
  657. /// <remarks>TrySetWidth can only be called when AutoSize is true (or being set to true).</remarks>
  658. /// <param name="desiredWidth"></param>
  659. /// <param name="resultWidth">
  660. /// Contains the width that would result if <see cref="Width"/> were set to
  661. /// <paramref name="desiredWidth"/>"/>
  662. /// </param>
  663. /// <returns>
  664. /// <see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False
  665. /// otherwise.
  666. /// </returns>
  667. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  668. {
  669. int w = desiredWidth;
  670. bool canSetWidth;
  671. switch (Width)
  672. {
  673. case Dim.DimCombine _:
  674. case Dim.DimView _:
  675. case Dim.DimFill _:
  676. // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  677. w = Width.Anchor (w);
  678. canSetWidth = !ValidatePosDim;
  679. break;
  680. case Dim.DimFactor factor:
  681. // Tries to get the SuperView Width otherwise the view Width.
  682. int sw = SuperView is { } ? SuperView.Frame.Width : w;
  683. if (factor.IsFromRemaining ())
  684. {
  685. sw -= Frame.X;
  686. }
  687. w = Width.Anchor (sw);
  688. canSetWidth = !ValidatePosDim;
  689. break;
  690. default:
  691. canSetWidth = true;
  692. break;
  693. }
  694. resultWidth = w;
  695. return canSetWidth;
  696. }
  697. /// <summary>Resizes the View to fit the specified size. Factors in the HotKey.</summary>
  698. /// <remarks>ResizeBoundsToFit can only be called when AutoSize is true (or being set to true).</remarks>
  699. /// <param name="size"></param>
  700. /// <returns>whether the Bounds was changed or not</returns>
  701. private bool ResizeBoundsToFit (Size size)
  702. {
  703. //if (AutoSize == false) {
  704. // throw new InvalidOperationException ("ResizeBoundsToFit can only be called when AutoSize is true");
  705. //}
  706. var boundsChanged = false;
  707. bool canSizeW = TrySetWidth (size.Width - GetHotKeySpecifierLength (), out int rW);
  708. bool canSizeH = TrySetHeight (size.Height - GetHotKeySpecifierLength (false), out int rH);
  709. if (canSizeW)
  710. {
  711. boundsChanged = true;
  712. _width = rW;
  713. }
  714. if (canSizeH)
  715. {
  716. boundsChanged = true;
  717. _height = rH;
  718. }
  719. if (boundsChanged)
  720. {
  721. Bounds = new (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  722. }
  723. return boundsChanged;
  724. }
  725. #endregion AutoSize
  726. #region Layout Engine
  727. /// <summary>
  728. /// Controls how the View's <see cref="Frame"/> is computed during <see cref="LayoutSubviews"/>. If the style is
  729. /// set to <see cref="LayoutStyle.Absolute"/>, LayoutSubviews does not change the <see cref="Frame"/>. If the style is
  730. /// <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using the <see cref="X"/>, <see cref="Y"/>,
  731. /// <see cref="Width"/>, and <see cref="Height"/> properties.
  732. /// </summary>
  733. /// <remarks>
  734. /// <para>
  735. /// Setting this property to <see cref="LayoutStyle.Absolute"/> will cause <see cref="Frame"/> to determine the
  736. /// size and position of the view. <see cref="X"/> and <see cref="Y"/> will be set to <see cref="Dim.DimAbsolute"/>
  737. /// using <see cref="Frame"/>.
  738. /// </para>
  739. /// <para>
  740. /// Setting this property to <see cref="LayoutStyle.Computed"/> will cause the view to use the
  741. /// <see cref="LayoutSubviews"/> method to size and position of the view. If either of the <see cref="X"/> and
  742. /// <see cref="Y"/> properties are `null` they will be set to <see cref="Pos.PosAbsolute"/> using the current value
  743. /// of <see cref="Frame"/>. If either of the <see cref="Width"/> and <see cref="Height"/> properties are `null`
  744. /// they will be set to <see cref="Dim.DimAbsolute"/> using <see cref="Frame"/>.
  745. /// </para>
  746. /// </remarks>
  747. /// <value>The layout style.</value>
  748. public LayoutStyle LayoutStyle
  749. {
  750. get
  751. {
  752. if (_x is Pos.PosAbsolute
  753. && _y is Pos.PosAbsolute
  754. && _width is Dim.DimAbsolute
  755. && _height is Dim.DimAbsolute)
  756. {
  757. return LayoutStyle.Absolute;
  758. }
  759. return LayoutStyle.Computed;
  760. }
  761. }
  762. #endregion Layout Engine
  763. internal bool LayoutNeeded { get; private set; } = true;
  764. #nullable enable
  765. /// <summary>Finds which view that belong to the <paramref name="start"/> superview at the provided location.</summary>
  766. /// <param name="start">The superview where to look for.</param>
  767. /// <param name="x">The column location in the superview.</param>
  768. /// <param name="y">The row location in the superview.</param>
  769. /// <returns>
  770. /// The view that was found at the <paramref name="x"/> and <paramref name="y"/> coordinates.
  771. /// <see langword="null"/> if no view was found.
  772. /// </returns>
  773. // CONCURRENCY: This method is not thread-safe. Undefined behavior and likely program crashes are exposed by unsynchronized access to InternalSubviews.
  774. internal static View? FindDeepestView (View? start, int x, int y)
  775. {
  776. if (start is null || !start.Visible)
  777. {
  778. return null;
  779. }
  780. if (!start.Frame.Contains (x, y))
  781. {
  782. return null;
  783. }
  784. Adornment? found = null;
  785. if (start.Margin.Thickness.Contains (start.Frame, x, y))
  786. {
  787. found = start.Margin;
  788. }
  789. else if (start.Border.Thickness.Contains (
  790. start.Border.Frame with
  791. {
  792. X = start.Frame.X + start.Border.Frame.X,
  793. Y = start.Frame.Y + start.Border.Frame.Y
  794. },
  795. x,
  796. y))
  797. {
  798. found = start.Border;
  799. }
  800. else if (start.Padding.Thickness.Contains (
  801. start.Padding.Frame with
  802. {
  803. X = start.Frame.X + start.Padding.Frame.X,
  804. Y = start.Frame.Y + start.Padding.Frame.Y
  805. },
  806. x,
  807. y))
  808. {
  809. found = start.Padding;
  810. }
  811. Point boundsOffset = start.GetBoundsOffset ();
  812. if (found is { })
  813. {
  814. start = found;
  815. boundsOffset = found.Parent.Frame.Location;
  816. }
  817. if (start.InternalSubviews is { Count: > 0 })
  818. {
  819. int rx = x - (start.Frame.X + boundsOffset.X);
  820. int ry = y - (start.Frame.Y + boundsOffset.Y);
  821. for (int i = start.InternalSubviews.Count - 1; i >= 0; i--)
  822. {
  823. View v = start.InternalSubviews [i];
  824. if (v.Visible && v.Frame.Contains (rx, ry))
  825. {
  826. View? deep = FindDeepestView (v, rx, ry);
  827. return deep ?? v;
  828. }
  829. }
  830. }
  831. return start;
  832. }
  833. #nullable restore
  834. /// <summary>
  835. /// Gets a new location of the <see cref="View"/> that is within the Bounds of the <paramref name="top"/>'s
  836. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  837. /// </summary>
  838. /// <remarks>
  839. /// If <paramref name="top"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  840. /// <see cref="Application.Top"/> the position will be bound by the <see cref="ConsoleDriver.Cols"/> and
  841. /// <see cref="ConsoleDriver.Rows"/>.
  842. /// </remarks>
  843. /// <param name="top">The View that is to be moved.</param>
  844. /// <param name="targetX">The target x location.</param>
  845. /// <param name="targetY">The target y location.</param>
  846. /// <param name="nx">The x location that will ensure <paramref name="top"/> will be visible.</param>
  847. /// <param name="ny">The y location that will ensure <paramref name="top"/> will be visible.</param>
  848. /// <param name="menuBar">The new top most menuBar</param>
  849. /// <param name="statusBar">The new top most statusBar</param>
  850. /// <returns>
  851. /// Either <see cref="Application.Top"/> (if <paramref name="top"/> does not have a Super View) or
  852. /// <paramref name="top"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  853. /// </returns>
  854. internal static View GetLocationThatFits (
  855. View top,
  856. int targetX,
  857. int targetY,
  858. out int nx,
  859. out int ny,
  860. out MenuBar menuBar,
  861. out StatusBar statusBar
  862. )
  863. {
  864. int maxDimension;
  865. View superView;
  866. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  867. {
  868. maxDimension = Driver.Cols;
  869. superView = Application.Top;
  870. }
  871. else
  872. {
  873. // Use the SuperView's Bounds, not Frame
  874. maxDimension = top.SuperView.Bounds.Width;
  875. superView = top.SuperView;
  876. }
  877. if (superView.Margin is { } && superView == top.SuperView)
  878. {
  879. maxDimension -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  880. }
  881. if (top.Frame.Width <= maxDimension)
  882. {
  883. nx = Math.Max (targetX, 0);
  884. nx = nx + top.Frame.Width > maxDimension ? Math.Max (maxDimension - top.Frame.Width, 0) : nx;
  885. if (nx > top.Frame.X + top.Frame.Width)
  886. {
  887. nx = Math.Max (top.Frame.Right, 0);
  888. }
  889. }
  890. else
  891. {
  892. nx = targetX;
  893. }
  894. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  895. bool menuVisible, statusVisible;
  896. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  897. {
  898. menuVisible = Application.Top.MenuBar?.Visible == true;
  899. menuBar = Application.Top.MenuBar;
  900. }
  901. else
  902. {
  903. View t = top.SuperView;
  904. while (t is not Toplevel)
  905. {
  906. t = t.SuperView;
  907. }
  908. menuVisible = ((Toplevel)t).MenuBar?.Visible == true;
  909. menuBar = ((Toplevel)t).MenuBar;
  910. }
  911. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  912. {
  913. maxDimension = menuVisible ? 1 : 0;
  914. }
  915. else
  916. {
  917. maxDimension = 0;
  918. }
  919. ny = Math.Max (targetY, maxDimension);
  920. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  921. {
  922. statusVisible = Application.Top.StatusBar?.Visible == true;
  923. statusBar = Application.Top.StatusBar;
  924. }
  925. else
  926. {
  927. View t = top.SuperView;
  928. while (t is not Toplevel)
  929. {
  930. t = t.SuperView;
  931. }
  932. statusVisible = ((Toplevel)t).StatusBar?.Visible == true;
  933. statusBar = ((Toplevel)t).StatusBar;
  934. }
  935. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  936. {
  937. maxDimension = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  938. }
  939. else
  940. {
  941. maxDimension = statusVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  942. }
  943. if (superView.Margin is { } && superView == top.SuperView)
  944. {
  945. maxDimension -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  946. }
  947. ny = Math.Min (ny, maxDimension);
  948. if (top.Frame.Height <= maxDimension)
  949. {
  950. ny = ny + top.Frame.Height > maxDimension
  951. ? Math.Max (maxDimension - top.Frame.Height, menuVisible ? 1 : 0)
  952. : ny;
  953. if (ny > top.Frame.Y + top.Frame.Height)
  954. {
  955. ny = Math.Max (top.Frame.Bottom, 0);
  956. }
  957. }
  958. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  959. return superView;
  960. }
  961. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  962. /// <remarks>
  963. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  964. /// otherwise changed.
  965. /// </remarks>
  966. public event EventHandler<LayoutEventArgs> LayoutComplete;
  967. /// <summary>Fired after the View's <see cref="LayoutSubviews"/> method has completed.</summary>
  968. /// <remarks>
  969. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has
  970. /// otherwise changed.
  971. /// </remarks>
  972. public event EventHandler<LayoutEventArgs> LayoutStarted;
  973. /// <summary>
  974. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in response
  975. /// to the container view or terminal resizing.
  976. /// </summary>
  977. /// <remarks>
  978. /// <para>
  979. /// The position and dimensions of the view are indeterminate until the view has been initialized. Therefore, the
  980. /// behavior of this method is indeterminate if <see cref="IsInitialized"/> is <see langword="false"/>.
  981. /// </para>
  982. /// <para>Raises the <see cref="LayoutComplete"/> event) before it returns.</para>
  983. /// </remarks>
  984. public virtual void LayoutSubviews ()
  985. {
  986. if (!IsInitialized)
  987. {
  988. Debug.WriteLine (
  989. $"WARNING: LayoutSubviews called before view has been initialized. This is likely a bug in {this}"
  990. );
  991. }
  992. if (!LayoutNeeded)
  993. {
  994. return;
  995. }
  996. LayoutAdornments ();
  997. Rectangle oldBounds = Bounds;
  998. OnLayoutStarted (new () { OldBounds = oldBounds });
  999. SetTextFormatterSize ();
  1000. // Sort out the dependencies of the X, Y, Width, Height properties
  1001. HashSet<View> nodes = new ();
  1002. HashSet<(View, View)> edges = new ();
  1003. CollectAll (this, ref nodes, ref edges);
  1004. List<View> ordered = TopologicalSort (SuperView, nodes, edges);
  1005. foreach (View v in ordered)
  1006. {
  1007. LayoutSubview (v, new (GetBoundsOffset (), Bounds.Size));
  1008. }
  1009. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  1010. // Use LayoutSubview with the Frame of the 'from'
  1011. if (SuperView is { } && GetTopSuperView () is { } && LayoutNeeded && edges.Count > 0)
  1012. {
  1013. foreach ((View from, View to) in edges)
  1014. {
  1015. LayoutSubview (to, from.Frame);
  1016. }
  1017. }
  1018. LayoutNeeded = false;
  1019. OnLayoutComplete (new () { OldBounds = oldBounds });
  1020. }
  1021. /// <summary>Indicates that the view does not need to be laid out.</summary>
  1022. protected void ClearLayoutNeeded () { LayoutNeeded = false; }
  1023. /// <summary>
  1024. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views
  1025. /// have been laid out.
  1026. /// </summary>
  1027. internal virtual void OnLayoutComplete (LayoutEventArgs args) { LayoutComplete?.Invoke (this, args); }
  1028. /// <summary>
  1029. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews
  1030. /// have been laid out.
  1031. /// </summary>
  1032. internal virtual void OnLayoutStarted (LayoutEventArgs args) { LayoutStarted?.Invoke (this, args); }
  1033. /// <summary>
  1034. /// Called whenever the view needs to be resized. This is called whenever <see cref="Frame"/>,
  1035. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, or <see cref="View.Height"/> changes.
  1036. /// </summary>
  1037. /// <remarks>
  1038. /// <para>
  1039. /// Determines the relative bounds of the <see cref="View"/> and its <see cref="Frame"/>s, and then calls
  1040. /// <see cref="SetRelativeLayout(Rectangle)"/> to update the view.
  1041. /// </para>
  1042. /// </remarks>
  1043. internal void OnResizeNeeded ()
  1044. {
  1045. // TODO: Identify a real-world use-case where this API should be virtual.
  1046. // TODO: Until then leave it `internal` and non-virtual
  1047. // First try SuperView.Bounds, then Application.Top, then Driver.Bounds.
  1048. // Finally, if none of those are valid, use int.MaxValue (for Unit tests).
  1049. Rectangle relativeBounds = SuperView is { IsInitialized: true } ? SuperView.Bounds :
  1050. Application.Top is { } && Application.Top.IsInitialized ? Application.Top.Bounds :
  1051. Application.Driver?.Bounds ?? new Rectangle (0, 0, int.MaxValue, int.MaxValue);
  1052. SetRelativeLayout (relativeBounds);
  1053. // TODO: Determine what, if any of the below is actually needed here.
  1054. if (IsInitialized)
  1055. {
  1056. if (AutoSize)
  1057. {
  1058. SetFrameToFitText ();
  1059. SetTextFormatterSize ();
  1060. }
  1061. LayoutAdornments ();
  1062. SetNeedsDisplay ();
  1063. SetNeedsLayout ();
  1064. }
  1065. }
  1066. /// <summary>
  1067. /// Sets the internal <see cref="LayoutNeeded"/> flag for this View and all of it's subviews and it's SuperView.
  1068. /// The main loop will call SetRelativeLayout and LayoutSubviews for any view with <see cref="LayoutNeeded"/> set.
  1069. /// </summary>
  1070. internal void SetNeedsLayout ()
  1071. {
  1072. if (LayoutNeeded)
  1073. {
  1074. return;
  1075. }
  1076. LayoutNeeded = true;
  1077. foreach (View view in Subviews)
  1078. {
  1079. view.SetNeedsLayout ();
  1080. }
  1081. TextFormatter.NeedsFormat = true;
  1082. SuperView?.SetNeedsLayout ();
  1083. }
  1084. /// <summary>
  1085. /// Applies the view's position (<see cref="X"/>, <see cref="Y"/>) and dimension (<see cref="Width"/>, and
  1086. /// <see cref="Height"/>) to <see cref="Frame"/>, given a rectangle describing the SuperView's Bounds (nominally the
  1087. /// same as <c>this.SuperView.Bounds</c>).
  1088. /// </summary>
  1089. /// <param name="superviewBounds">
  1090. /// The rectangle describing the SuperView's Bounds (nominally the same as
  1091. /// <c>this.SuperView.Bounds</c>).
  1092. /// </param>
  1093. internal void SetRelativeLayout (Rectangle superviewBounds)
  1094. {
  1095. Debug.Assert (_x is { });
  1096. Debug.Assert (_y is { });
  1097. Debug.Assert (_width is { });
  1098. Debug.Assert (_height is { });
  1099. int newX, newW, newY, newH;
  1100. var autosize = Size.Empty;
  1101. if (AutoSize)
  1102. {
  1103. // Note this is global to this function and used as such within the local functions defined
  1104. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  1105. autosize = GetAutoSize ();
  1106. }
  1107. // TODO: Since GetNewLocationAndDimension does not depend on View, it can be moved into PosDim.cs
  1108. // TODO: to make architecture more clean. Do this after DimAuto is implemented and the
  1109. // TODO: View.AutoSize stuff is removed.
  1110. // Returns the new dimension (width or height) and location (x or y) for the View given
  1111. // the superview's Bounds
  1112. // the current Pos (View.X or View.Y)
  1113. // the current Dim (View.Width or View.Height)
  1114. // This method is called recursively if pos is Pos.PosCombine
  1115. (int newLocation, int newDimension) GetNewLocationAndDimension (
  1116. bool width,
  1117. Rectangle superviewBounds,
  1118. Pos pos,
  1119. Dim dim,
  1120. int autosizeDimension
  1121. )
  1122. {
  1123. // Gets the new dimension (width or height, dependent on `width`) of the given Dim given:
  1124. // location: the current location (x or y)
  1125. // dimension: the new dimension (width or height) (if relevant for Dim type)
  1126. // autosize: the size to use if autosize = true
  1127. // This method is recursive if d is Dim.DimCombine
  1128. int GetNewDimension (Dim d, int location, int dimension, int autosize)
  1129. {
  1130. int newDimension;
  1131. switch (d)
  1132. {
  1133. case Dim.DimCombine combine:
  1134. // TODO: Move combine logic into DimCombine?
  1135. int leftNewDim = GetNewDimension (combine._left, location, dimension, autosize);
  1136. int rightNewDim = GetNewDimension (combine._right, location, dimension, autosize);
  1137. if (combine._add)
  1138. {
  1139. newDimension = leftNewDim + rightNewDim;
  1140. }
  1141. else
  1142. {
  1143. newDimension = leftNewDim - rightNewDim;
  1144. }
  1145. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  1146. break;
  1147. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  1148. newDimension = d.Anchor (dimension);
  1149. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  1150. break;
  1151. case Dim.DimAbsolute:
  1152. // DimAbsolute.Anchor (int width) ignores width and returns n
  1153. newDimension = Math.Max (d.Anchor (0), 0);
  1154. // BUGBUG: AutoSize does two things: makes text fit AND changes the view's dimensions
  1155. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  1156. break;
  1157. case Dim.DimFill:
  1158. default:
  1159. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  1160. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  1161. break;
  1162. }
  1163. return newDimension;
  1164. }
  1165. int newDimension, newLocation;
  1166. int superviewDimension = width ? superviewBounds.Width : superviewBounds.Height;
  1167. // Determine new location
  1168. switch (pos)
  1169. {
  1170. case Pos.PosCenter posCenter:
  1171. // For Center, the dimension is dependent on location, but we need to force getting the dimension first
  1172. // using a location of 0
  1173. newDimension = Math.Max (GetNewDimension (dim, 0, superviewDimension, autosizeDimension), 0);
  1174. newLocation = posCenter.Anchor (superviewDimension - newDimension);
  1175. newDimension = Math.Max (
  1176. GetNewDimension (dim, newLocation, superviewDimension, autosizeDimension),
  1177. 0
  1178. );
  1179. break;
  1180. case Pos.PosCombine combine:
  1181. // TODO: Move combine logic into PosCombine?
  1182. int left, right;
  1183. (left, newDimension) = GetNewLocationAndDimension (
  1184. width,
  1185. superviewBounds,
  1186. combine._left,
  1187. dim,
  1188. autosizeDimension
  1189. );
  1190. (right, newDimension) = GetNewLocationAndDimension (
  1191. width,
  1192. superviewBounds,
  1193. combine._right,
  1194. dim,
  1195. autosizeDimension
  1196. );
  1197. if (combine._add)
  1198. {
  1199. newLocation = left + right;
  1200. }
  1201. else
  1202. {
  1203. newLocation = left - right;
  1204. }
  1205. newDimension = Math.Max (
  1206. GetNewDimension (dim, newLocation, superviewDimension, autosizeDimension),
  1207. 0
  1208. );
  1209. break;
  1210. case Pos.PosAnchorEnd:
  1211. case Pos.PosAbsolute:
  1212. case Pos.PosFactor:
  1213. case Pos.PosFunc:
  1214. case Pos.PosView:
  1215. default:
  1216. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  1217. newDimension = Math.Max (
  1218. GetNewDimension (dim, newLocation, superviewDimension, autosizeDimension),
  1219. 0
  1220. );
  1221. break;
  1222. }
  1223. return (newLocation, newDimension);
  1224. }
  1225. // horizontal/width
  1226. (newX, newW) = GetNewLocationAndDimension (true, superviewBounds, _x, _width, autosize.Width);
  1227. // vertical/height
  1228. (newY, newH) = GetNewLocationAndDimension (false, superviewBounds, _y, _height, autosize.Height);
  1229. Rectangle r = new (newX, newY, newW, newH);
  1230. if (Frame != r)
  1231. {
  1232. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  1233. // the view LayoutStyle.Absolute.
  1234. _frame = r;
  1235. if (_x is Pos.PosAbsolute)
  1236. {
  1237. _x = Frame.X;
  1238. }
  1239. if (_y is Pos.PosAbsolute)
  1240. {
  1241. _y = Frame.Y;
  1242. }
  1243. if (_width is Dim.DimAbsolute)
  1244. {
  1245. _width = Frame.Width;
  1246. }
  1247. if (_height is Dim.DimAbsolute)
  1248. {
  1249. _height = Frame.Height;
  1250. }
  1251. SetNeedsLayout ();
  1252. SetNeedsDisplay ();
  1253. }
  1254. if (AutoSize)
  1255. {
  1256. if (autosize.Width == 0 || autosize.Height == 0)
  1257. {
  1258. // Set the frame. Do NOT use `Frame` as it overwrites X, Y, Width, and Height, making
  1259. // the view LayoutStyle.Absolute.
  1260. _frame = _frame with { Size = autosize };
  1261. if (autosize.Width == 0)
  1262. {
  1263. _width = 0;
  1264. }
  1265. if (autosize.Height == 0)
  1266. {
  1267. _height = 0;
  1268. }
  1269. }
  1270. else if (!SetFrameToFitText ())
  1271. {
  1272. SetTextFormatterSize ();
  1273. }
  1274. SetNeedsLayout ();
  1275. SetNeedsDisplay ();
  1276. }
  1277. }
  1278. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1279. {
  1280. // BUGBUG: This should really only work on initialized subviews
  1281. foreach (View v in from.InternalSubviews /*.Where(v => v.IsInitialized)*/)
  1282. {
  1283. nNodes.Add (v);
  1284. if (v.LayoutStyle != LayoutStyle.Computed)
  1285. {
  1286. continue;
  1287. }
  1288. CollectPos (v.X, v, ref nNodes, ref nEdges);
  1289. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  1290. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  1291. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  1292. }
  1293. }
  1294. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1295. {
  1296. switch (dim)
  1297. {
  1298. case Dim.DimView dv:
  1299. // See #2461
  1300. //if (!from.InternalSubviews.Contains (dv.Target)) {
  1301. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  1302. //}
  1303. if (dv.Target != this)
  1304. {
  1305. nEdges.Add ((dv.Target, from));
  1306. }
  1307. return;
  1308. case Dim.DimCombine dc:
  1309. CollectDim (dc._left, from, ref nNodes, ref nEdges);
  1310. CollectDim (dc._right, from, ref nNodes, ref nEdges);
  1311. break;
  1312. }
  1313. }
  1314. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1315. {
  1316. switch (pos)
  1317. {
  1318. case Pos.PosView pv:
  1319. // See #2461
  1320. //if (!from.InternalSubviews.Contains (pv.Target)) {
  1321. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  1322. //}
  1323. if (pv.Target != this)
  1324. {
  1325. nEdges.Add ((pv.Target, from));
  1326. }
  1327. return;
  1328. case Pos.PosCombine pc:
  1329. CollectPos (pc._left, from, ref nNodes, ref nEdges);
  1330. CollectPos (pc._right, from, ref nNodes, ref nEdges);
  1331. break;
  1332. }
  1333. }
  1334. // https://en.wikipedia.org/wiki/Topological_sorting
  1335. internal static List<View> TopologicalSort (
  1336. View superView,
  1337. IEnumerable<View> nodes,
  1338. ICollection<(View From, View To)> edges
  1339. )
  1340. {
  1341. List<View> result = new ();
  1342. // Set of all nodes with no incoming edges
  1343. HashSet<View> noEdgeNodes = new (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  1344. while (noEdgeNodes.Any ())
  1345. {
  1346. // remove a node n from S
  1347. View n = noEdgeNodes.First ();
  1348. noEdgeNodes.Remove (n);
  1349. // add n to tail of L
  1350. if (n != superView)
  1351. {
  1352. result.Add (n);
  1353. }
  1354. // for each node m with an edge e from n to m do
  1355. foreach ((View From, View To) e in edges.Where (e => e.From.Equals (n)).ToArray ())
  1356. {
  1357. View m = e.To;
  1358. // remove edge e from the graph
  1359. edges.Remove (e);
  1360. // if m has no other incoming edges then
  1361. if (edges.All (me => !me.To.Equals (m)) && m != superView)
  1362. {
  1363. // insert m into S
  1364. noEdgeNodes.Add (m);
  1365. }
  1366. }
  1367. }
  1368. if (!edges.Any ())
  1369. {
  1370. return result;
  1371. }
  1372. foreach ((View from, View to) in edges)
  1373. {
  1374. if (from == to)
  1375. {
  1376. // if not yet added to the result, add it and remove from edge
  1377. if (result.Find (v => v == from) is null)
  1378. {
  1379. result.Add (from);
  1380. }
  1381. edges.Remove ((from, to));
  1382. }
  1383. else if (from.SuperView == to.SuperView)
  1384. {
  1385. // if 'from' is not yet added to the result, add it
  1386. if (result.Find (v => v == from) is null)
  1387. {
  1388. result.Add (from);
  1389. }
  1390. // if 'to' is not yet added to the result, add it
  1391. if (result.Find (v => v == to) is null)
  1392. {
  1393. result.Add (to);
  1394. }
  1395. // remove from edge
  1396. edges.Remove ((from, to));
  1397. }
  1398. else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to))
  1399. {
  1400. if (ReferenceEquals (from.SuperView, to))
  1401. {
  1402. throw new InvalidOperationException (
  1403. $"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\")."
  1404. );
  1405. }
  1406. throw new InvalidOperationException (
  1407. $"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?"
  1408. );
  1409. }
  1410. }
  1411. // return L (a topologically sorted order)
  1412. return result;
  1413. } // TopologicalSort
  1414. private void LayoutSubview (View v, Rectangle contentArea)
  1415. {
  1416. //if (v.LayoutStyle == LayoutStyle.Computed) {
  1417. v.SetRelativeLayout (contentArea);
  1418. //}
  1419. v.LayoutSubviews ();
  1420. v.LayoutNeeded = false;
  1421. }
  1422. #region Diagnostics
  1423. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  1424. private Dim VerifyIsInitialized (Dim dim, string member)
  1425. {
  1426. #if DEBUG
  1427. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1428. {
  1429. Debug.WriteLine (
  1430. $"WARNING: \"{this}\" has not been initialized; {member} is indeterminate: {dim}. This is potentially a bug."
  1431. );
  1432. }
  1433. #endif // DEBUG
  1434. return dim;
  1435. }
  1436. // Diagnostics to highlight when X or Y is read before the view has been initialized
  1437. private Pos VerifyIsInitialized (Pos pos, string member)
  1438. {
  1439. #if DEBUG
  1440. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized)
  1441. {
  1442. Debug.WriteLine (
  1443. $"WARNING: \"{this}\" has not been initialized; {member} is indeterminate {pos}. This is potentially a bug."
  1444. );
  1445. }
  1446. #endif // DEBUG
  1447. return pos;
  1448. }
  1449. /// <summary>Gets or sets whether validation of <see cref="Pos"/> and <see cref="Dim"/> occurs.</summary>
  1450. /// <remarks>
  1451. /// Setting this to <see langword="true"/> will enable validation of <see cref="X"/>, <see cref="Y"/>,
  1452. /// <see cref="Width"/>, and <see cref="Height"/> during set operations and in <see cref="LayoutSubviews"/>. If invalid
  1453. /// settings are discovered exceptions will be thrown indicating the error. This will impose a performance penalty and
  1454. /// thus should only be used for debugging.
  1455. /// </remarks>
  1456. public bool ValidatePosDim { get; set; }
  1457. #endregion
  1458. }