ViewLayout.cs 58 KB

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