View.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. //
  2. // Authors:
  3. // Miguel de Icaza ([email protected])
  4. //
  5. // Pending:
  6. // - Check for NeedDisplay on the hierarchy and repaint
  7. // - Layout support
  8. // - "Colors" type or "Attributes" type?
  9. // - What to surface as "BackgroundCOlor" when clearing a window, an attribute or colors?
  10. //
  11. // Optimziations
  12. // - Add rendering limitation to the exposed area
  13. using System;
  14. using System.Collections;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using NStack;
  18. namespace Terminal.Gui {
  19. /// <summary>
  20. /// Text alignment enumeration, controls how text is displayed.
  21. /// </summary>
  22. public enum TextAlignment {
  23. /// <summary>
  24. /// Aligns the text to the left of the frame.
  25. /// </summary>
  26. Left,
  27. /// <summary>
  28. /// Aligns the text to the right side of the frame.
  29. /// </summary>
  30. Right,
  31. /// <summary>
  32. /// Centers the text in the frame.
  33. /// </summary>
  34. Centered,
  35. /// <summary>
  36. /// Shows the text as justified text in the frame.
  37. /// </summary>
  38. Justified
  39. }
  40. /// <summary>
  41. /// Determines the LayoutStyle for a view, if Absolute, during LayoutSubviews, the
  42. /// value from the Frame will be used, if the value is Computed, then the Frame
  43. /// will be updated from the X, Y Pos objects and the Width and Height Dim objects.
  44. /// </summary>
  45. public enum LayoutStyle {
  46. /// <summary>
  47. /// The position and size of the view are based on the Frame value.
  48. /// </summary>
  49. Absolute,
  50. /// <summary>
  51. /// The position and size of the view will be computed based on the
  52. /// X, Y, Width and Height properties and set on the Frame.
  53. /// </summary>
  54. Computed
  55. }
  56. /// <summary>
  57. /// View is the base class for all views on the screen and represents a visible element that can render itself and contains zero or more nested views.
  58. /// </summary>
  59. /// <remarks>
  60. /// <para>
  61. /// The View defines the base functionality for user interface elements in Terminal.Gui. Views
  62. /// can contain one or more subviews, can respond to user input and render themselves on the screen.
  63. /// </para>
  64. /// <para>
  65. /// Views supports two layout styles: Absolute or Computed. The choice as to which layout style is used by the View
  66. /// is determined when the View is initizlied. To create a View using Absolute layout, call a constructor that takes a
  67. /// Rect parameter to specify the absolute position and size (the <c>View.<see cref="Frame "/></c>)/. To create a View
  68. /// using Computed layout use a constructor that does not take a Rect parametr and set the X, Y, Width and Height
  69. /// properties on the view. Both approaches use coordinates that are relative to the container they are being added to.
  70. /// </para>
  71. /// <para>
  72. /// To switch between Absolute and Computed layout, use the <see cref="LayoutStyle"/> property.
  73. /// </para>
  74. /// <para>
  75. /// Computed layout is more flexible and supports dynamic console apps where controls adjust layout
  76. /// as the terminal resizes or other Views change size or position. The X, Y, Width and Height
  77. /// properties are Dim and Pos objects that dynamically update the position of a view.
  78. /// The X and Y properties are of type <see cref="Pos"/>
  79. /// and you can use either absolute positions, percentages or anchor
  80. /// points. The Width and Height properties are of type
  81. /// <see cref="Dim"/> and can use absolute position,
  82. /// percentages and anchors. These are useful as they will take
  83. /// care of repositioning views when view's frames are resized or
  84. /// if the terminal size changes.
  85. /// </para>
  86. /// <para>
  87. /// Absolute layout requires specifying coordiantes and sizes of Views explicitly, and the
  88. /// View will typcialy stay in a fixed position and size. To change the position and size use the
  89. /// <see cref="Frame"/> property.
  90. /// </para>
  91. /// <para>
  92. /// Subviews (child views) can be added to a View by calling the <see cref="Add(View)"/> method.
  93. /// The container of a View can be accessed with the <see cref="SuperView"/> property.
  94. /// </para>
  95. /// <para>
  96. /// To flag a region of the View's <see cref="Bounds"/> to be redrawn call <see cref="SetNeedsDisplay(Rect)"/>. To flag the entire view
  97. /// for redraw call <see cref="SetNeedsDisplay()"/>.
  98. /// </para>
  99. /// <para>
  100. /// Views have a <see cref="ColorScheme"/> property that defines the default colors that subviews
  101. /// should use for rendering. This ensures that the views fit in the context where
  102. /// they are being used, and allows for themes to be plugged in. For example, the
  103. /// default colors for windows and toplevels uses a blue background, while it uses
  104. /// a white background for dialog boxes and a red background for errors.
  105. /// </para>
  106. /// <para>
  107. /// Subclasses should not rely on <see cref="ColorScheme"/> being
  108. /// set at construction time. If a <see cref="ColorScheme"/> is not set on a view, the view will inherit the
  109. /// value from its <see cref="SuperView"/> and the value might only be valid once a view has been
  110. /// added to a SuperView.
  111. /// </para>
  112. /// <para>
  113. /// By using <see cref="ColorScheme"/> applications will work both
  114. /// in color as well as black and white displays.
  115. /// </para>
  116. /// <para>
  117. /// Views that are focusable should implement the <see cref="PositionCursor"/> to make sure that
  118. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  119. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  120. /// the last focused view. So views should make sure that they place the cursor
  121. /// in a visually sensible place.
  122. /// </para>
  123. /// <para>
  124. /// The <see cref="LayoutSubviews"/> method is invoked when the size or layout of a view has
  125. /// changed. The default processing system will keep the size and dimensions
  126. /// for views that use the <see cref="LayoutStyle.Absolute"/>, and will recompute the
  127. /// frames for the vies that use <see cref="LayoutStyle.Computed"/>.
  128. /// </para>
  129. /// </remarks>
  130. public class View : Responder, IEnumerable {
  131. internal enum Direction {
  132. Forward,
  133. Backward
  134. }
  135. // container == SuperView
  136. View container = null;
  137. View focused = null;
  138. Direction focusDirection;
  139. /// <summary>
  140. /// Event fired when the view is added.
  141. /// </summary>
  142. public Action<View> AddedView;
  143. /// <summary>
  144. /// Event fired when the view is being removing.
  145. /// </summary>
  146. public Action<View> RemovingView;
  147. /// <summary>
  148. /// Event fired when the view gets focus.
  149. /// </summary>
  150. public Action<FocusEventArgs> Enter;
  151. /// <summary>
  152. /// Event fired when the view looses focus.
  153. /// </summary>
  154. public Action<FocusEventArgs> Leave;
  155. /// <summary>
  156. /// Event fired when the view receives the mouse event for the first time.
  157. /// </summary>
  158. public Action<MouseEventArgs> MouseEnter;
  159. /// <summary>
  160. /// Event fired when the view receives a mouse event for the last time.
  161. /// </summary>
  162. public Action<MouseEventArgs> MouseLeave;
  163. /// <summary>
  164. /// Event fired when a mouse event is generated.
  165. /// </summary>
  166. public Action<MouseEventArgs> MouseClick;
  167. internal Direction FocusDirection {
  168. get => SuperView?.FocusDirection ?? focusDirection;
  169. set {
  170. if (SuperView != null)
  171. SuperView.FocusDirection = value;
  172. else
  173. focusDirection = value;
  174. }
  175. }
  176. /// <summary>
  177. /// Points to the current driver in use by the view, it is a convenience property
  178. /// for simplifying the development of new views.
  179. /// </summary>
  180. public static ConsoleDriver Driver { get { return Application.Driver; } }
  181. static IList<View> empty = new List<View> (0).AsReadOnly ();
  182. // This is null, and allocated on demand.
  183. List<View> subviews;
  184. /// <summary>
  185. /// This returns a list of the subviews contained by this view.
  186. /// </summary>
  187. /// <value>The subviews.</value>
  188. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  189. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  190. // to make the same mistakes our users make when they poke at the Subviews.
  191. internal IList<View> InternalSubviews => subviews ?? empty;
  192. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  193. // The frame for the object. Superview relative.
  194. Rect frame;
  195. /// <summary>
  196. /// Gets or sets an identifier for the view;
  197. /// </summary>
  198. /// <value>The identifier.</value>
  199. /// <remarks>The id should be unique across all Views that share a SuperView.</remarks>
  200. public ustring Id { get; set; } = "";
  201. /// <summary>
  202. /// Returns a value indicating if this View is currently on Top (Active)
  203. /// </summary>
  204. public bool IsCurrentTop {
  205. get {
  206. return Application.Current == this;
  207. }
  208. }
  209. /// <summary>
  210. /// Gets or sets a value indicating whether this <see cref="View"/> wants mouse position reports.
  211. /// </summary>
  212. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  213. public virtual bool WantMousePositionReports { get; set; } = false;
  214. /// <summary>
  215. /// Gets or sets a value indicating whether this <see cref="View"/> want continuous button pressed event.
  216. /// </summary>
  217. public virtual bool WantContinuousButtonPressed { get; set; } = false;
  218. /// <summary>
  219. /// Gets or sets the frame for the view. The frame is relative to the view's container (<see cref="SuperView"/>).
  220. /// </summary>
  221. /// <value>The frame.</value>
  222. /// <remarks>
  223. /// <para>
  224. /// Change the Frame when using the <see cref="LayoutStyle.Absolute"/> layout style to move or resize views.
  225. /// </para>
  226. /// <para>
  227. /// Altering the Frame of a view will trigger the redrawing of the
  228. /// view as well as the redrawing of the affected regions of the <see cref="SuperView"/>.
  229. /// </para>
  230. /// </remarks>
  231. public virtual Rect Frame {
  232. get => frame;
  233. set {
  234. if (SuperView != null) {
  235. SuperView.SetNeedsDisplay (frame);
  236. SuperView.SetNeedsDisplay (value);
  237. }
  238. frame = value;
  239. SetNeedsLayout ();
  240. SetNeedsDisplay (frame);
  241. }
  242. }
  243. /// <summary>
  244. /// Gets an enumerator that enumerates the subviews in this view.
  245. /// </summary>
  246. /// <returns>The enumerator.</returns>
  247. public IEnumerator GetEnumerator ()
  248. {
  249. foreach (var v in InternalSubviews)
  250. yield return v;
  251. }
  252. LayoutStyle layoutStyle;
  253. /// <summary>
  254. /// Controls how the View's <see cref="Frame"/> is computed during the LayoutSubviews method, if the style is set to <see cref="LayoutStyle.Absolute"/>,
  255. /// LayoutSubviews does not change the <see cref="Frame"/>. If the style is <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using
  256. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  257. /// </summary>
  258. /// <value>The layout style.</value>
  259. public LayoutStyle LayoutStyle {
  260. get => layoutStyle;
  261. set {
  262. layoutStyle = value;
  263. SetNeedsLayout ();
  264. }
  265. }
  266. /// <summary>
  267. /// The bounds represent the View-relative rectangle used for this view; the area inside of the view.
  268. /// </summary>
  269. /// <value>The bounds.</value>
  270. /// <remarks>
  271. /// <para>
  272. /// Updates to the Bounds update the <see cref="Frame"/>,
  273. /// and has the same side effects as updating the <see cref="Frame"/>.
  274. /// </para>
  275. /// <para>
  276. /// Because <see cref="Bounds"/> coordinates are relative to the upper-left corner of the <see cref="View"/>,
  277. /// the coordinates of the upper-left corner of the rectangle returned by this property are (0,0).
  278. /// Use this property to obtain the size and coordinates of the client area of the
  279. /// control for tasks such as drawing on the surface of the control.
  280. /// </para>
  281. /// </remarks>
  282. public Rect Bounds {
  283. get => new Rect (Point.Empty, Frame.Size);
  284. set {
  285. Frame = new Rect (frame.Location, value.Size);
  286. }
  287. }
  288. Pos x, y;
  289. /// <summary>
  290. /// Gets or sets the X position for the view (the column). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  291. /// </summary>
  292. /// <value>The X Position.</value>
  293. /// <remarks>
  294. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  295. /// </remarks>
  296. public Pos X {
  297. get => x;
  298. set {
  299. x = value;
  300. SetNeedsLayout ();
  301. SetNeedsDisplay (frame);
  302. }
  303. }
  304. /// <summary>
  305. /// Gets or sets the Y position for the view (the row). Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  306. /// </summary>
  307. /// <value>The y position (line).</value>
  308. /// <remarks>
  309. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  310. /// </remarks>
  311. public Pos Y {
  312. get => y;
  313. set {
  314. y = value;
  315. SetNeedsLayout ();
  316. SetNeedsDisplay (frame);
  317. }
  318. }
  319. Dim width, height;
  320. /// <summary>
  321. /// Gets or sets the width of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  322. /// </summary>
  323. /// <value>The width.</value>
  324. /// <remarks>
  325. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  326. /// </remarks>
  327. public Dim Width {
  328. get => width;
  329. set {
  330. width = value;
  331. SetNeedsLayout ();
  332. SetNeedsDisplay (frame);
  333. }
  334. }
  335. /// <summary>
  336. /// Gets or sets the height of the view. Only used whe <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  337. /// </summary>
  338. /// <value>The height.</value>
  339. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  340. public Dim Height {
  341. get => height;
  342. set {
  343. height = value;
  344. SetNeedsLayout ();
  345. SetNeedsDisplay (frame);
  346. }
  347. }
  348. /// <summary>
  349. /// Returns the container for this view, or null if this view has not been added to a container.
  350. /// </summary>
  351. /// <value>The super view.</value>
  352. public View SuperView => container;
  353. /// <summary>
  354. /// Initializes a new instance of a <see cref="LayoutStyle.Absolute"/> <see cref="View"/> class with the absolute
  355. /// dimensions specified in the <c>frame</c> parameter.
  356. /// </summary>
  357. /// <param name="frame">The region covered by this view.</param>
  358. /// <remarks>
  359. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Absolute"/>. Use <see cref="View()"/> to
  360. /// initialize a View with <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>
  361. /// </remarks>
  362. public View (Rect frame)
  363. {
  364. this.Frame = frame;
  365. CanFocus = false;
  366. LayoutStyle = LayoutStyle.Absolute;
  367. }
  368. /// <summary>
  369. /// Initializes a new instance of <see cref="LayoutStyle.Computed"/> <see cref="View"/> class.
  370. /// </summary>
  371. /// <remarks>
  372. /// Use <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties to dynamically control the size and location of the view.
  373. /// </remarks>
  374. /// <remarks>
  375. /// This constructor intitalize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>.
  376. /// Use <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties to dynamically control the size and location of the view.
  377. /// </remarks>
  378. public View ()
  379. {
  380. CanFocus = false;
  381. LayoutStyle = LayoutStyle.Computed;
  382. x = Pos.At (0);
  383. y = Pos.At (0);
  384. Height = 0;
  385. Width = 0;
  386. }
  387. /// <summary>
  388. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  389. /// </summary>
  390. public void SetNeedsDisplay ()
  391. {
  392. SetNeedsDisplay (Bounds);
  393. }
  394. internal bool layoutNeeded = true;
  395. internal void SetNeedsLayout ()
  396. {
  397. if (layoutNeeded)
  398. return;
  399. layoutNeeded = true;
  400. if (SuperView == null)
  401. return;
  402. SuperView.SetNeedsLayout ();
  403. }
  404. /// <summary>
  405. /// Flags the view-relative region on this View as needing to be repainted.
  406. /// </summary>
  407. /// <param name="region">The view-relative region that must be flagged for repaint.</param>
  408. public void SetNeedsDisplay (Rect region)
  409. {
  410. if (NeedDisplay == null || NeedDisplay.IsEmpty)
  411. NeedDisplay = region;
  412. else {
  413. var x = Math.Min (NeedDisplay.X, region.X);
  414. var y = Math.Min (NeedDisplay.Y, region.Y);
  415. var w = Math.Max (NeedDisplay.Width, region.Width);
  416. var h = Math.Max (NeedDisplay.Height, region.Height);
  417. NeedDisplay = new Rect (x, y, w, h);
  418. }
  419. if (container != null)
  420. container.ChildNeedsDisplay ();
  421. if (subviews == null)
  422. return;
  423. foreach (var view in subviews)
  424. if (view.Frame.IntersectsWith (region)) {
  425. var childRegion = Rect.Intersect (view.Frame, region);
  426. childRegion.X -= view.Frame.X;
  427. childRegion.Y -= view.Frame.Y;
  428. view.SetNeedsDisplay (childRegion);
  429. }
  430. }
  431. internal bool childNeedsDisplay;
  432. /// <summary>
  433. /// Indicates that any child views (in the <see cref="Subviews"/> list) need to be repainted.
  434. /// </summary>
  435. public void ChildNeedsDisplay ()
  436. {
  437. childNeedsDisplay = true;
  438. if (container != null)
  439. container.ChildNeedsDisplay ();
  440. }
  441. /// <summary>
  442. /// Adds a subview (child) to this view.
  443. /// </summary>
  444. /// <remarks>
  445. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property. See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  446. /// </remarks>
  447. public virtual void Add (View view)
  448. {
  449. if (view == null)
  450. return;
  451. if (subviews == null)
  452. subviews = new List<View> ();
  453. subviews.Add (view);
  454. view.container = this;
  455. OnAddedView (view);
  456. if (view.CanFocus)
  457. CanFocus = true;
  458. SetNeedsLayout ();
  459. SetNeedsDisplay ();
  460. }
  461. /// <summary>
  462. /// Adds the specified views (children) to the view.
  463. /// </summary>
  464. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  465. /// <remarks>
  466. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property. See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  467. /// </remarks>
  468. public void Add (params View [] views)
  469. {
  470. if (views == null)
  471. return;
  472. foreach (var view in views)
  473. Add (view);
  474. }
  475. /// <summary>
  476. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  477. /// </summary>
  478. public virtual void RemoveAll ()
  479. {
  480. if (subviews == null)
  481. return;
  482. while (subviews.Count > 0) {
  483. Remove (subviews [0]);
  484. }
  485. }
  486. /// <summary>
  487. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  488. /// </summary>
  489. /// <remarks>
  490. /// </remarks>
  491. public virtual void Remove (View view)
  492. {
  493. if (view == null || subviews == null)
  494. return;
  495. OnRemovingView (view);
  496. SetNeedsLayout ();
  497. SetNeedsDisplay ();
  498. var touched = view.Frame;
  499. subviews.Remove (view);
  500. view.container = null;
  501. if (subviews.Count < 1)
  502. this.CanFocus = false;
  503. foreach (var v in subviews) {
  504. if (v.Frame.IntersectsWith (touched))
  505. view.SetNeedsDisplay ();
  506. }
  507. }
  508. void PerformActionForSubview (View subview, Action<View> action)
  509. {
  510. if (subviews.Contains (subview)) {
  511. action (subview);
  512. }
  513. SetNeedsDisplay ();
  514. subview.SetNeedsDisplay ();
  515. }
  516. /// <summary>
  517. /// Brings the specified subview to the front so it is drawn on top of any other views.
  518. /// </summary>
  519. /// <param name="subview">The subview to send to the front</param>
  520. /// <remarks>
  521. /// <seealso cref="SendSubviewToBack"/>.
  522. /// </remarks>
  523. public void BringSubviewToFront (View subview)
  524. {
  525. PerformActionForSubview (subview, x => {
  526. subviews.Remove (x);
  527. subviews.Add (x);
  528. });
  529. }
  530. /// <summary>
  531. /// Sends the specified subview to the front so it is the first view drawn
  532. /// </summary>
  533. /// <param name="subview">The subview to send to the front</param>
  534. /// <remarks>
  535. /// <seealso cref="BringSubviewToFront(View)"/>.
  536. /// </remarks>
  537. public void SendSubviewToBack (View subview)
  538. {
  539. PerformActionForSubview (subview, x => {
  540. subviews.Remove (x);
  541. subviews.Insert (0, subview);
  542. });
  543. }
  544. /// <summary>
  545. /// Moves the subview backwards in the hierarchy, only one step
  546. /// </summary>
  547. /// <param name="subview">The subview to send backwards</param>
  548. /// <remarks>
  549. /// If you want to send the view all the way to the back use SendSubviewToBack.
  550. /// </remarks>
  551. public void SendSubviewBackwards (View subview)
  552. {
  553. PerformActionForSubview (subview, x => {
  554. var idx = subviews.IndexOf (x);
  555. if (idx > 0) {
  556. subviews.Remove (x);
  557. subviews.Insert (idx - 1, x);
  558. }
  559. });
  560. }
  561. /// <summary>
  562. /// Moves the subview backwards in the hierarchy, only one step
  563. /// </summary>
  564. /// <param name="subview">The subview to send backwards</param>
  565. /// <remarks>
  566. /// If you want to send the view all the way to the back use SendSubviewToBack.
  567. /// </remarks>
  568. public void BringSubviewForward (View subview)
  569. {
  570. PerformActionForSubview (subview, x => {
  571. var idx = subviews.IndexOf (x);
  572. if (idx + 1 < subviews.Count) {
  573. subviews.Remove (x);
  574. subviews.Insert (idx + 1, x);
  575. }
  576. });
  577. }
  578. /// <summary>
  579. /// Clears the view region with the current color.
  580. /// </summary>
  581. /// <remarks>
  582. /// <para>
  583. /// This clears the entire region used by this view.
  584. /// </para>
  585. /// </remarks>
  586. public void Clear ()
  587. {
  588. var h = Frame.Height;
  589. var w = Frame.Width;
  590. for (int line = 0; line < h; line++) {
  591. Move (0, line);
  592. for (int col = 0; col < w; col++)
  593. Driver.AddRune (' ');
  594. }
  595. }
  596. /// <summary>
  597. /// Clears the specified region with the current color.
  598. /// </summary>
  599. /// <remarks>
  600. /// </remarks>
  601. /// <param name="regionScreen">The screen-relative region to clear.</param>
  602. public void Clear (Rect regionScreen)
  603. {
  604. var h = regionScreen.Height;
  605. var w = regionScreen.Width;
  606. for (int line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  607. Driver.Move (regionScreen.X, line);
  608. for (int col = 0; col < w; col++)
  609. Driver.AddRune (' ');
  610. }
  611. }
  612. /// <summary>
  613. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  614. /// </summary>
  615. /// <param name="col">View-relative column.</param>
  616. /// <param name="row">View-relative row.</param>
  617. /// <param name="rcol">Absolute column; screen-relative.</param>
  618. /// <param name="rrow">Absolute row; screen-relative.</param>
  619. /// <param name="clipped">Whether to clip the result of the ViewToScreen method, if set to <c>true</c>, the rcol, rrow values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).</param>
  620. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  621. {
  622. // Computes the real row, col relative to the screen.
  623. rrow = row + frame.Y;
  624. rcol = col + frame.X;
  625. var ccontainer = container;
  626. while (ccontainer != null) {
  627. rrow += ccontainer.frame.Y;
  628. rcol += ccontainer.frame.X;
  629. ccontainer = ccontainer.container;
  630. }
  631. // The following ensures that the cursor is always in the screen boundaries.
  632. if (clipped) {
  633. rrow = Math.Min (rrow, Driver.Rows - 1);
  634. rcol = Math.Min (rcol, Driver.Cols - 1);
  635. }
  636. }
  637. /// <summary>
  638. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  639. /// </summary>
  640. /// <returns>The mapped point.</returns>
  641. /// <param name="x">X screen-coordinate point.</param>
  642. /// <param name="y">Y screen-coordinate point.</param>
  643. public Point ScreenToView (int x, int y)
  644. {
  645. if (SuperView == null) {
  646. return new Point (x - Frame.X, y - frame.Y);
  647. } else {
  648. var parent = SuperView.ScreenToView (x, y);
  649. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  650. }
  651. }
  652. /// <summary>
  653. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  654. /// </summary>
  655. internal Rect ViewToScreen (Rect region)
  656. {
  657. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  658. return new Rect (x, y, region.Width, region.Height);
  659. }
  660. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  661. internal Rect ScreenClip (Rect regionScreen)
  662. {
  663. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  664. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  665. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  666. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  667. return new Rect (x, y, w, h);
  668. }
  669. /// <summary>
  670. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  671. /// </summary>
  672. /// <returns>The existing driver's clip region, which can be then re-eapplied by setting <c><see cref="Driver"/>.Clip</c> (<see cref="ConsoleDriver.Clip"/>).</returns>
  673. /// <remarks>
  674. /// <see cref="Bounds"/> is View-relative.
  675. /// </remarks>
  676. public Rect ClipToBounds ()
  677. {
  678. return SetClip (Bounds);
  679. }
  680. /// <summary>
  681. /// Sets the clip region to the specified view-relative region.
  682. /// </summary>
  683. /// <returns>The previous screen-relative clip region.</returns>
  684. /// <param name="region">View-relative clip region.</param>
  685. public Rect SetClip (Rect region)
  686. {
  687. var previous = Driver.Clip;
  688. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  689. return previous;
  690. }
  691. /// <summary>
  692. /// Draws a frame in the current view, clipped by the boundary of this view
  693. /// </summary>
  694. /// <param name="region">View-relative region for the frame to be drawn.</param>
  695. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  696. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  697. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  698. {
  699. var scrRect = ViewToScreen (region);
  700. var savedClip = ClipToBounds ();
  701. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  702. Driver.Clip = savedClip;
  703. }
  704. /// <summary>
  705. /// Utility function to draw strings that contain a hotkey.
  706. /// </summary>
  707. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  708. /// <param name="hotColor">Hot color.</param>
  709. /// <param name="normalColor">Normal color.</param>
  710. /// <remarks>
  711. /// The hotkey is any character following an underscore ('_') character.</remarks>
  712. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  713. {
  714. Driver.SetAttribute (normalColor);
  715. foreach (var rune in text) {
  716. if (rune == '_') {
  717. Driver.SetAttribute (hotColor);
  718. continue;
  719. }
  720. Driver.AddRune (rune);
  721. Driver.SetAttribute (normalColor);
  722. }
  723. }
  724. /// <summary>
  725. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  726. /// </summary>
  727. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  728. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  729. /// <param name="scheme">The color scheme to use.</param>
  730. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  731. {
  732. if (focused)
  733. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  734. else
  735. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  736. }
  737. /// <summary>
  738. /// This moves the cursor to the specified column and row in the view.
  739. /// </summary>
  740. /// <returns>The move.</returns>
  741. /// <param name="col">Col.</param>
  742. /// <param name="row">Row.</param>
  743. public void Move (int col, int row)
  744. {
  745. ViewToScreen (col, row, out var rcol, out var rrow);
  746. Driver.Move (rcol, rrow);
  747. }
  748. /// <summary>
  749. /// Positions the cursor in the right position based on the currently focused view in the chain.
  750. /// </summary>
  751. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  752. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  753. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  754. /// the last focused view. Views should make sure that they place the cursor
  755. /// in a visually sensible place.
  756. public virtual void PositionCursor ()
  757. {
  758. if (focused != null)
  759. focused.PositionCursor ();
  760. else
  761. Move (frame.X, frame.Y);
  762. }
  763. /// <inheritdoc/>
  764. public override bool HasFocus {
  765. get {
  766. return base.HasFocus;
  767. }
  768. internal set {
  769. if (base.HasFocus != value)
  770. if (value)
  771. OnEnter ();
  772. else
  773. OnLeave ();
  774. SetNeedsDisplay ();
  775. base.HasFocus = value;
  776. // Remove focus down the chain of subviews if focus is removed
  777. if (!value && focused != null) {
  778. focused.OnLeave ();
  779. focused.HasFocus = false;
  780. focused = null;
  781. }
  782. }
  783. }
  784. /// <summary>
  785. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  786. /// </summary>
  787. public class FocusEventArgs : EventArgs {
  788. /// <summary>
  789. /// Constructs.
  790. /// </summary>
  791. public FocusEventArgs () { }
  792. /// <summary>
  793. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  794. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  795. /// </summary>
  796. public bool Handled { get; set; }
  797. }
  798. /// <inheritdoc/>
  799. public override void OnAddedView (View view)
  800. {
  801. AddedView?.Invoke (view);
  802. }
  803. /// <inheritdoc/>
  804. public override void OnRemovingView (View view)
  805. {
  806. RemovingView?.Invoke (view);
  807. }
  808. /// <inheritdoc/>
  809. public override bool OnEnter ()
  810. {
  811. FocusEventArgs args = new FocusEventArgs ();
  812. Enter?.Invoke (args);
  813. if (args.Handled)
  814. return true;
  815. if (base.OnEnter ())
  816. return true;
  817. return false;
  818. }
  819. /// <inheritdoc/>
  820. public override bool OnLeave ()
  821. {
  822. FocusEventArgs args = new FocusEventArgs ();
  823. Leave?.Invoke (args);
  824. if (args.Handled)
  825. return true;
  826. if (base.OnLeave ())
  827. return true;
  828. return false;
  829. }
  830. /// <summary>
  831. /// Returns the currently focused view inside this view, or null if nothing is focused.
  832. /// </summary>
  833. /// <value>The focused.</value>
  834. public View Focused => focused;
  835. /// <summary>
  836. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  837. /// </summary>
  838. /// <value>The most focused.</value>
  839. public View MostFocused {
  840. get {
  841. if (Focused == null)
  842. return null;
  843. var most = Focused.MostFocused;
  844. if (most != null)
  845. return most;
  846. return Focused;
  847. }
  848. }
  849. /// <summary>
  850. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  851. /// color scheme.
  852. /// </summary>
  853. public ColorScheme ColorScheme {
  854. get {
  855. if (colorScheme == null)
  856. return SuperView?.ColorScheme;
  857. return colorScheme;
  858. }
  859. set {
  860. colorScheme = value;
  861. }
  862. }
  863. ColorScheme colorScheme;
  864. /// <summary>
  865. /// Displays the specified character in the specified column and row of the View.
  866. /// </summary>
  867. /// <param name="col">Column (view-relative).</param>
  868. /// <param name="row">Row (view-relative).</param>
  869. /// <param name="ch">Ch.</param>
  870. public void AddRune (int col, int row, Rune ch)
  871. {
  872. if (row < 0 || col < 0)
  873. return;
  874. if (row > frame.Height - 1 || col > frame.Width - 1)
  875. return;
  876. Move (col, row);
  877. Driver.AddRune (ch);
  878. }
  879. /// <summary>
  880. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  881. /// </summary>
  882. protected void ClearNeedsDisplay ()
  883. {
  884. NeedDisplay = Rect.Empty;
  885. childNeedsDisplay = false;
  886. }
  887. /// <summary>
  888. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  889. /// </summary>
  890. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  891. /// <remarks>
  892. /// <para>
  893. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  894. /// </para>
  895. /// <para>
  896. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  897. /// the last color that was set globaly on the driver.
  898. /// </para>
  899. /// <para>
  900. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  901. /// larger than the <c>region</c> parameter.
  902. /// </para>
  903. /// </remarks>
  904. public virtual void Redraw (Rect bounds)
  905. {
  906. var clipRect = new Rect (Point.Empty, frame.Size);
  907. // Invoke DrawContentEvent
  908. OnDrawContent (bounds);
  909. if (subviews != null) {
  910. foreach (var view in subviews) {
  911. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  912. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  913. // FIXED: optimize this by computing the intersection of region and view.Bounds
  914. if (view.layoutNeeded)
  915. view.LayoutSubviews ();
  916. Application.CurrentView = view;
  917. // Draw the subview
  918. // Use the view's bounds (view-relative; Location will always be (0,0) because
  919. view.Redraw (view.Bounds);
  920. }
  921. view.NeedDisplay = Rect.Empty;
  922. view.childNeedsDisplay = false;
  923. }
  924. }
  925. }
  926. ClearNeedsDisplay ();
  927. }
  928. /// <summary>
  929. /// Event invoked when the content area of the View is to be drawn.
  930. /// </summary>
  931. /// <remarks>
  932. /// <para>
  933. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  934. /// </para>
  935. /// <para>
  936. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  937. /// </para>
  938. /// </remarks>
  939. public Action<Rect> DrawContent;
  940. /// <summary>
  941. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  942. /// </summary>
  943. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  944. /// <remarks>
  945. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  946. /// </remarks>
  947. public virtual void OnDrawContent (Rect viewport)
  948. {
  949. DrawContent?.Invoke (viewport);
  950. }
  951. /// <summary>
  952. /// Causes the specified subview to have focus.
  953. /// </summary>
  954. /// <param name="view">View.</param>
  955. public void SetFocus (View view)
  956. {
  957. if (view == null)
  958. return;
  959. //Console.WriteLine ($"Request to focus {view}");
  960. if (!view.CanFocus)
  961. return;
  962. if (focused == view)
  963. return;
  964. // Make sure that this view is a subview
  965. View c;
  966. for (c = view.container; c != null; c = c.container)
  967. if (c == this)
  968. break;
  969. if (c == null)
  970. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  971. if (focused != null)
  972. focused.HasFocus = false;
  973. focused = view;
  974. focused.HasFocus = true;
  975. focused.EnsureFocus ();
  976. // Send focus upwards
  977. SuperView?.SetFocus (this);
  978. }
  979. /// <summary>
  980. /// Defines the event arguments for <see cref="KeyEvent"/>
  981. /// </summary>
  982. public class KeyEventEventArgs : EventArgs {
  983. /// <summary>
  984. /// Constructs.
  985. /// </summary>
  986. /// <param name="ke"></param>
  987. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  988. /// <summary>
  989. /// The <see cref="KeyEvent"/> for the event.
  990. /// </summary>
  991. public KeyEvent KeyEvent { get; set; }
  992. /// <summary>
  993. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  994. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  995. /// </summary>
  996. public bool Handled { get; set; } = false;
  997. }
  998. /// <summary>
  999. /// Invoked when a character key is pressed and occurs after the key up event.
  1000. /// </summary>
  1001. public Action<KeyEventEventArgs> KeyPress;
  1002. /// <inheritdoc/>
  1003. public override bool ProcessKey (KeyEvent keyEvent)
  1004. {
  1005. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1006. KeyPress?.Invoke (args);
  1007. if (args.Handled)
  1008. return true;
  1009. if (Focused?.ProcessKey (keyEvent) == true)
  1010. return true;
  1011. return false;
  1012. }
  1013. /// <inheritdoc/>
  1014. public override bool ProcessHotKey (KeyEvent keyEvent)
  1015. {
  1016. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1017. KeyPress?.Invoke (args);
  1018. if (args.Handled)
  1019. return true;
  1020. if (subviews == null || subviews.Count == 0)
  1021. return false;
  1022. foreach (var view in subviews)
  1023. if (view.SuperView.IsCurrentTop && view.ProcessHotKey (keyEvent))
  1024. return true;
  1025. return false;
  1026. }
  1027. /// <inheritdoc/>
  1028. public override bool ProcessColdKey (KeyEvent keyEvent)
  1029. {
  1030. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1031. KeyPress?.Invoke (args);
  1032. if (args.Handled)
  1033. return true;
  1034. if (subviews == null || subviews.Count == 0)
  1035. return false;
  1036. foreach (var view in subviews)
  1037. if (view.SuperView.IsCurrentTop && view.ProcessColdKey (keyEvent))
  1038. return true;
  1039. return false;
  1040. }
  1041. /// <summary>
  1042. /// Invoked when a key is pressed
  1043. /// </summary>
  1044. public Action<KeyEventEventArgs> KeyDown;
  1045. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1046. public override bool OnKeyDown (KeyEvent keyEvent)
  1047. {
  1048. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1049. KeyDown?.Invoke (args);
  1050. if (args.Handled)
  1051. return true;
  1052. if (subviews == null || subviews.Count == 0)
  1053. return false;
  1054. foreach (var view in subviews)
  1055. if (view.SuperView.IsCurrentTop && view.OnKeyDown (keyEvent))
  1056. return true;
  1057. return false;
  1058. }
  1059. /// <summary>
  1060. /// Invoked when a key is released
  1061. /// </summary>
  1062. public Action<KeyEventEventArgs> KeyUp;
  1063. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1064. public override bool OnKeyUp (KeyEvent keyEvent)
  1065. {
  1066. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1067. KeyUp?.Invoke (args);
  1068. if (args.Handled)
  1069. return true;
  1070. if (subviews == null || subviews.Count == 0)
  1071. return false;
  1072. foreach (var view in subviews)
  1073. if (view.SuperView.IsCurrentTop && view.OnKeyUp (keyEvent))
  1074. return true;
  1075. return false;
  1076. }
  1077. /// <summary>
  1078. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1079. /// </summary>
  1080. public void EnsureFocus ()
  1081. {
  1082. if (focused == null)
  1083. if (FocusDirection == Direction.Forward)
  1084. FocusFirst ();
  1085. else
  1086. FocusLast ();
  1087. }
  1088. /// <summary>
  1089. /// Focuses the first focusable subview if one exists.
  1090. /// </summary>
  1091. public void FocusFirst ()
  1092. {
  1093. if (subviews == null) {
  1094. SuperView?.SetFocus (this);
  1095. return;
  1096. }
  1097. foreach (var view in subviews) {
  1098. if (view.CanFocus) {
  1099. SetFocus (view);
  1100. return;
  1101. }
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Focuses the last focusable subview if one exists.
  1106. /// </summary>
  1107. public void FocusLast ()
  1108. {
  1109. if (subviews == null) {
  1110. SuperView?.SetFocus (this);
  1111. return;
  1112. }
  1113. for (int i = subviews.Count; i > 0;) {
  1114. i--;
  1115. View v = subviews [i];
  1116. if (v.CanFocus) {
  1117. SetFocus (v);
  1118. return;
  1119. }
  1120. }
  1121. }
  1122. /// <summary>
  1123. /// Focuses the previous view.
  1124. /// </summary>
  1125. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1126. public bool FocusPrev ()
  1127. {
  1128. FocusDirection = Direction.Backward;
  1129. if (subviews == null || subviews.Count == 0)
  1130. return false;
  1131. if (focused == null) {
  1132. FocusLast ();
  1133. return focused != null;
  1134. }
  1135. int focused_idx = -1;
  1136. for (int i = subviews.Count; i > 0;) {
  1137. i--;
  1138. View w = subviews [i];
  1139. if (w.HasFocus) {
  1140. if (w.FocusPrev ())
  1141. return true;
  1142. focused_idx = i;
  1143. continue;
  1144. }
  1145. if (w.CanFocus && focused_idx != -1) {
  1146. focused.HasFocus = false;
  1147. if (w != null && w.CanFocus)
  1148. w.FocusLast ();
  1149. SetFocus (w);
  1150. return true;
  1151. }
  1152. }
  1153. if (focused != null) {
  1154. focused.HasFocus = false;
  1155. focused = null;
  1156. }
  1157. return false;
  1158. }
  1159. /// <summary>
  1160. /// Focuses the next view.
  1161. /// </summary>
  1162. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1163. public bool FocusNext ()
  1164. {
  1165. FocusDirection = Direction.Forward;
  1166. if (subviews == null || subviews.Count == 0)
  1167. return false;
  1168. if (focused == null) {
  1169. FocusFirst ();
  1170. return focused != null;
  1171. }
  1172. int n = subviews.Count;
  1173. int focused_idx = -1;
  1174. for (int i = 0; i < n; i++) {
  1175. View w = subviews [i];
  1176. if (w.HasFocus) {
  1177. if (w.FocusNext ())
  1178. return true;
  1179. focused_idx = i;
  1180. continue;
  1181. }
  1182. if (w.CanFocus && focused_idx != -1) {
  1183. focused.HasFocus = false;
  1184. if (w != null && w.CanFocus)
  1185. w.FocusFirst ();
  1186. SetFocus (w);
  1187. return true;
  1188. }
  1189. }
  1190. if (focused != null) {
  1191. focused.HasFocus = false;
  1192. focused = null;
  1193. }
  1194. return false;
  1195. }
  1196. /// <summary>
  1197. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1198. /// </summary>
  1199. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1200. /// <remarks>
  1201. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1202. /// </remarks>
  1203. internal void SetRelativeLayout (Rect hostFrame)
  1204. {
  1205. int w, h, _x, _y;
  1206. if (x is Pos.PosCenter) {
  1207. if (width == null)
  1208. w = hostFrame.Width;
  1209. else
  1210. w = width.Anchor (hostFrame.Width);
  1211. _x = x.Anchor (hostFrame.Width - w);
  1212. } else {
  1213. if (x == null)
  1214. _x = 0;
  1215. else
  1216. _x = x.Anchor (hostFrame.Width);
  1217. if (width == null)
  1218. w = hostFrame.Width;
  1219. else if (width is Dim.DimFactor && !((Dim.DimFactor)width).IsFromRemaining ())
  1220. w = width.Anchor (hostFrame.Width);
  1221. else
  1222. w = Math.Max (width.Anchor (hostFrame.Width - _x), 0);
  1223. }
  1224. if (y is Pos.PosCenter) {
  1225. if (height == null)
  1226. h = hostFrame.Height;
  1227. else
  1228. h = height.Anchor (hostFrame.Height);
  1229. _y = y.Anchor (hostFrame.Height - h);
  1230. } else {
  1231. if (y == null)
  1232. _y = 0;
  1233. else
  1234. _y = y.Anchor (hostFrame.Height);
  1235. if (height == null)
  1236. h = hostFrame.Height;
  1237. else if (height is Dim.DimFactor && !((Dim.DimFactor)height).IsFromRemaining ())
  1238. h = height.Anchor (hostFrame.Height);
  1239. else
  1240. h = Math.Max (height.Anchor (hostFrame.Height - _y), 0);
  1241. }
  1242. Frame = new Rect (_x, _y, w, h);
  1243. }
  1244. // https://en.wikipedia.org/wiki/Topological_sorting
  1245. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1246. {
  1247. var result = new List<View> ();
  1248. // Set of all nodes with no incoming edges
  1249. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1250. while (S.Any ()) {
  1251. // remove a node n from S
  1252. var n = S.First ();
  1253. S.Remove (n);
  1254. // add n to tail of L
  1255. if (n != this?.SuperView)
  1256. result.Add (n);
  1257. // for each node m with an edge e from n to m do
  1258. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1259. var m = e.To;
  1260. // remove edge e from the graph
  1261. edges.Remove (e);
  1262. // if m has no other incoming edges then
  1263. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1264. // insert m into S
  1265. S.Add (m);
  1266. }
  1267. }
  1268. }
  1269. if (edges.Any ()) {
  1270. if (!object.ReferenceEquals(edges.First ().From, edges.First ().To)) {
  1271. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {edges.First ().From}. Did you forget to add it to {this}?");
  1272. } else {
  1273. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1274. }
  1275. } else {
  1276. // return L (a topologically sorted order)
  1277. return result;
  1278. }
  1279. }
  1280. /// <summary>
  1281. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1282. /// </summary>
  1283. public class LayoutEventArgs : EventArgs {
  1284. /// <summary>
  1285. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1286. /// </summary>
  1287. public Rect OldBounds { get; set; }
  1288. }
  1289. /// <summary>
  1290. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1291. /// </summary>
  1292. /// <remarks>
  1293. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1294. /// </remarks>
  1295. public Action<LayoutEventArgs> LayoutComplete;
  1296. /// <summary>
  1297. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> after all sub-views have been laid out.
  1298. /// </summary>
  1299. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1300. {
  1301. LayoutComplete?.Invoke (args);
  1302. }
  1303. /// <summary>
  1304. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1305. /// response to the container view or terminal resizing.
  1306. /// </summary>
  1307. /// <remarks>
  1308. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1309. /// </remarks>
  1310. public virtual void LayoutSubviews ()
  1311. {
  1312. if (!layoutNeeded)
  1313. return;
  1314. Rect oldBounds = Bounds;
  1315. // Sort out the dependencies of the X, Y, Width, Height properties
  1316. var nodes = new HashSet<View> ();
  1317. var edges = new HashSet<(View, View)> ();
  1318. foreach (var v in InternalSubviews) {
  1319. nodes.Add (v);
  1320. if (v.LayoutStyle == LayoutStyle.Computed) {
  1321. if (v.X is Pos.PosView vX)
  1322. edges.Add ((vX.Target, v));
  1323. if (v.Y is Pos.PosView vY)
  1324. edges.Add ((vY.Target, v));
  1325. if (v.Width is Dim.DimView vWidth)
  1326. edges.Add ((vWidth.Target, v));
  1327. if (v.Height is Dim.DimView vHeight)
  1328. edges.Add ((vHeight.Target, v));
  1329. }
  1330. }
  1331. var ordered = TopologicalSort (nodes, edges);
  1332. foreach (var v in ordered) {
  1333. if (v.LayoutStyle == LayoutStyle.Computed)
  1334. v.SetRelativeLayout (Frame);
  1335. v.LayoutSubviews ();
  1336. v.layoutNeeded = false;
  1337. }
  1338. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1339. SetRelativeLayout (Frame);
  1340. }
  1341. layoutNeeded = false;
  1342. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1343. }
  1344. /// <summary>
  1345. /// A generic virtual method at the level of View to manipulate any hot-keys.
  1346. /// </summary>
  1347. /// <param name="text">The text to manipulate.</param>
  1348. /// <param name="hotKey">The hot-key to look for.</param>
  1349. /// <param name="hotPos">The returning hot-key position.</param>
  1350. /// <param name="showHotKey">The character immediately to the right relative to the hot-key position</param>
  1351. /// <returns>It aims to facilitate the preparation for <see cref="TextAlignment"/> procedures.</returns>
  1352. public virtual ustring GetTextFromHotKey (ustring text, Rune hotKey, out int hotPos, out Rune showHotKey)
  1353. {
  1354. Rune hot_key = (Rune)0;
  1355. int hot_pos = -1;
  1356. ustring shown_text = text;
  1357. // Use first hot_key char passed into 'hotKey'.
  1358. int i = 0;
  1359. foreach (Rune c in shown_text) {
  1360. if ((char)c != 0xFFFD) {
  1361. if (c == hotKey) {
  1362. hot_pos = i;
  1363. } else if (hot_pos > -1) {
  1364. hot_key = c;
  1365. break;
  1366. }
  1367. }
  1368. i++;
  1369. }
  1370. if (hot_pos == -1) {
  1371. // Use first upper-case char if there are no hot-key in the text.
  1372. i = 0;
  1373. foreach (Rune c in shown_text) {
  1374. if ((char)c != 0xFFFD) {
  1375. if (Rune.IsUpper (c)) {
  1376. hot_key = c;
  1377. hot_pos = i;
  1378. break;
  1379. }
  1380. }
  1381. i++;
  1382. }
  1383. } else {
  1384. // Use char after 'hotKey'
  1385. ustring start = "";
  1386. i = 0;
  1387. foreach (Rune c in shown_text) {
  1388. start += ustring.Make (c);
  1389. i++;
  1390. if (i == hot_pos)
  1391. break;
  1392. }
  1393. var st = shown_text;
  1394. shown_text = start;
  1395. i = 0;
  1396. foreach (Rune c in st) {
  1397. i++;
  1398. if (i > hot_pos + 1) {
  1399. shown_text += ustring.Make (c);
  1400. }
  1401. }
  1402. }
  1403. hotPos = hot_pos;
  1404. showHotKey = hot_key;
  1405. return shown_text;
  1406. }
  1407. /// <summary>
  1408. /// A generic virtual method at the level of View to manipulate any hot-keys with <see cref="TextAlignment"/> process.
  1409. /// </summary>
  1410. /// <param name="shown_text">The text to manipulate to align.</param>
  1411. /// <param name="hot_pos">The passed in hot-key position.</param>
  1412. /// <param name="c_hot_pos">The returning hot-key position.</param>
  1413. /// <param name="textAlignment">The <see cref="TextAlignment"/> to align to.</param>
  1414. /// <returns>It performs the <see cref="TextAlignment"/> process to the caller.</returns>
  1415. public virtual ustring GetTextAlignment (ustring shown_text, int hot_pos, out int c_hot_pos, TextAlignment textAlignment)
  1416. {
  1417. int start;
  1418. var caption = shown_text;
  1419. c_hot_pos = hot_pos;
  1420. if (Frame.Width > shown_text.Length + 1) {
  1421. switch (textAlignment) {
  1422. case TextAlignment.Left:
  1423. caption += new string (' ', Frame.Width - caption.RuneCount);
  1424. break;
  1425. case TextAlignment.Right:
  1426. start = Frame.Width - caption.RuneCount;
  1427. caption = $"{new string (' ', Frame.Width - caption.RuneCount)}{caption}";
  1428. if (c_hot_pos > -1) {
  1429. c_hot_pos += start;
  1430. }
  1431. break;
  1432. case TextAlignment.Centered:
  1433. start = Frame.Width / 2 - caption.RuneCount / 2;
  1434. caption = $"{new string (' ', start)}{caption}{new string (' ', Frame.Width - caption.RuneCount - start)}";
  1435. if (c_hot_pos > -1) {
  1436. c_hot_pos += start;
  1437. }
  1438. break;
  1439. case TextAlignment.Justified:
  1440. var words = caption.Split (" ");
  1441. var wLen = GetWordsLength (words, c_hot_pos, out int runeCount, out int w_hot_pos);
  1442. var space = (Frame.Width - runeCount) / (caption.Length - wLen);
  1443. caption = "";
  1444. for (int i = 0; i < words.Length; i++) {
  1445. if (i == words.Length - 1) {
  1446. caption += new string (' ', Frame.Width - caption.RuneCount - 1);
  1447. caption += words [i];
  1448. } else {
  1449. caption += words [i];
  1450. }
  1451. if (i < words.Length - 1) {
  1452. caption += new string (' ', space);
  1453. }
  1454. }
  1455. if (c_hot_pos > -1) {
  1456. c_hot_pos += w_hot_pos * space - space - w_hot_pos + 1;
  1457. }
  1458. break;
  1459. }
  1460. }
  1461. return caption;
  1462. }
  1463. int GetWordsLength (ustring [] words, int hotPos, out int runeCount, out int wordHotPos)
  1464. {
  1465. int length = 0;
  1466. int rCount = 0;
  1467. int wHotPos = -1;
  1468. for (int i = 0; i < words.Length; i++) {
  1469. if (wHotPos == -1 && rCount + words [i].RuneCount >= hotPos)
  1470. wHotPos = i;
  1471. length += words [i].Length;
  1472. rCount += words [i].RuneCount;
  1473. }
  1474. if (wHotPos == -1 && hotPos > -1)
  1475. wHotPos = words.Length;
  1476. runeCount = rCount;
  1477. wordHotPos = wHotPos;
  1478. return length;
  1479. }
  1480. /// <summary>
  1481. /// Pretty prints the View
  1482. /// </summary>
  1483. /// <returns></returns>
  1484. public override string ToString ()
  1485. {
  1486. return $"{GetType ().Name}({Id})({Frame})";
  1487. }
  1488. /// <summary>
  1489. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1490. /// </summary>
  1491. public class MouseEventArgs : EventArgs {
  1492. /// <summary>
  1493. /// Constructs.
  1494. /// </summary>
  1495. /// <param name="me"></param>
  1496. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  1497. /// <summary>
  1498. /// The <see cref="MouseEvent"/> for the event.
  1499. /// </summary>
  1500. public MouseEvent MouseEvent { get; set; }
  1501. /// <summary>
  1502. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1503. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1504. /// </summary>
  1505. public bool Handled { get; set; }
  1506. }
  1507. /// <inheritdoc/>
  1508. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1509. {
  1510. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1511. MouseEnter?.Invoke (args);
  1512. if (args.Handled)
  1513. return true;
  1514. if (base.OnMouseEnter (mouseEvent))
  1515. return true;
  1516. return false;
  1517. }
  1518. /// <inheritdoc/>
  1519. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1520. {
  1521. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1522. MouseLeave?.Invoke (args);
  1523. if (args.Handled)
  1524. return true;
  1525. if (base.OnMouseLeave (mouseEvent))
  1526. return true;
  1527. return false;
  1528. }
  1529. /// <summary>
  1530. /// Method invoked when a mouse event is generated
  1531. /// </summary>
  1532. /// <param name="mouseEvent"></param>
  1533. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1534. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1535. {
  1536. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1537. MouseClick?.Invoke (args);
  1538. if (args.Handled)
  1539. return true;
  1540. if (MouseEvent (mouseEvent))
  1541. return true;
  1542. return false;
  1543. }
  1544. }
  1545. }