View.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  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 a subview is being added to this view.
  141. /// </summary>
  142. public Action<View> Adding;
  143. /// <summary>
  144. /// Event fired when a subview is being removed from this view.
  145. /// </summary>
  146. public Action<View> Removing;
  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. OnAdding (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. OnRemoving (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. /// <summary>
  799. /// Method invoked when a subview is being added to this view.
  800. /// </summary>
  801. /// <param name="view">The subview being added.</param>
  802. public virtual void OnAdding (View view)
  803. {
  804. view.Adding?.Invoke (this);
  805. }
  806. /// <summary>
  807. /// Method invoked when a subview is being removed from this view.
  808. /// </summary>
  809. /// <param name="view">The subview being removed.</param>
  810. public virtual void OnRemoving (View view)
  811. {
  812. view.Removing?.Invoke (this);
  813. }
  814. /// <inheritdoc/>
  815. public override bool OnEnter ()
  816. {
  817. FocusEventArgs args = new FocusEventArgs ();
  818. Enter?.Invoke (args);
  819. if (args.Handled)
  820. return true;
  821. if (base.OnEnter ())
  822. return true;
  823. return false;
  824. }
  825. /// <inheritdoc/>
  826. public override bool OnLeave ()
  827. {
  828. FocusEventArgs args = new FocusEventArgs ();
  829. Leave?.Invoke (args);
  830. if (args.Handled)
  831. return true;
  832. if (base.OnLeave ())
  833. return true;
  834. return false;
  835. }
  836. /// <summary>
  837. /// Returns the currently focused view inside this view, or null if nothing is focused.
  838. /// </summary>
  839. /// <value>The focused.</value>
  840. public View Focused => focused;
  841. /// <summary>
  842. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  843. /// </summary>
  844. /// <value>The most focused.</value>
  845. public View MostFocused {
  846. get {
  847. if (Focused == null)
  848. return null;
  849. var most = Focused.MostFocused;
  850. if (most != null)
  851. return most;
  852. return Focused;
  853. }
  854. }
  855. /// <summary>
  856. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  857. /// color scheme.
  858. /// </summary>
  859. public ColorScheme ColorScheme {
  860. get {
  861. if (colorScheme == null)
  862. return SuperView?.ColorScheme;
  863. return colorScheme;
  864. }
  865. set {
  866. colorScheme = value;
  867. }
  868. }
  869. ColorScheme colorScheme;
  870. /// <summary>
  871. /// Displays the specified character in the specified column and row of the View.
  872. /// </summary>
  873. /// <param name="col">Column (view-relative).</param>
  874. /// <param name="row">Row (view-relative).</param>
  875. /// <param name="ch">Ch.</param>
  876. public void AddRune (int col, int row, Rune ch)
  877. {
  878. if (row < 0 || col < 0)
  879. return;
  880. if (row > frame.Height - 1 || col > frame.Width - 1)
  881. return;
  882. Move (col, row);
  883. Driver.AddRune (ch);
  884. }
  885. /// <summary>
  886. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  887. /// </summary>
  888. protected void ClearNeedsDisplay ()
  889. {
  890. NeedDisplay = Rect.Empty;
  891. childNeedsDisplay = false;
  892. }
  893. /// <summary>
  894. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  895. /// </summary>
  896. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  897. /// <remarks>
  898. /// <para>
  899. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  900. /// </para>
  901. /// <para>
  902. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  903. /// the last color that was set globaly on the driver.
  904. /// </para>
  905. /// <para>
  906. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  907. /// larger than the <c>region</c> parameter.
  908. /// </para>
  909. /// </remarks>
  910. public virtual void Redraw (Rect bounds)
  911. {
  912. var clipRect = new Rect (Point.Empty, frame.Size);
  913. // Invoke DrawContentEvent
  914. OnDrawContent (bounds);
  915. if (subviews != null) {
  916. foreach (var view in subviews) {
  917. if (view.NeedDisplay != null && (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay)) {
  918. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  919. // FIXED: optimize this by computing the intersection of region and view.Bounds
  920. if (view.layoutNeeded)
  921. view.LayoutSubviews ();
  922. Application.CurrentView = view;
  923. // Draw the subview
  924. // Use the view's bounds (view-relative; Location will always be (0,0) because
  925. view.Redraw (view.Bounds);
  926. }
  927. view.NeedDisplay = Rect.Empty;
  928. view.childNeedsDisplay = false;
  929. }
  930. }
  931. }
  932. ClearNeedsDisplay ();
  933. }
  934. /// <summary>
  935. /// Event invoked when the content area of the View is to be drawn.
  936. /// </summary>
  937. /// <remarks>
  938. /// <para>
  939. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  940. /// </para>
  941. /// <para>
  942. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  943. /// </para>
  944. /// </remarks>
  945. public Action<Rect> DrawContent;
  946. /// <summary>
  947. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  948. /// </summary>
  949. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  950. /// <remarks>
  951. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  952. /// </remarks>
  953. public virtual void OnDrawContent (Rect viewport)
  954. {
  955. DrawContent?.Invoke (viewport);
  956. }
  957. /// <summary>
  958. /// Causes the specified subview to have focus.
  959. /// </summary>
  960. /// <param name="view">View.</param>
  961. public void SetFocus (View view)
  962. {
  963. if (view == null)
  964. return;
  965. //Console.WriteLine ($"Request to focus {view}");
  966. if (!view.CanFocus)
  967. return;
  968. if (focused == view)
  969. return;
  970. // Make sure that this view is a subview
  971. View c;
  972. for (c = view.container; c != null; c = c.container)
  973. if (c == this)
  974. break;
  975. if (c == null)
  976. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  977. if (focused != null)
  978. focused.HasFocus = false;
  979. focused = view;
  980. focused.HasFocus = true;
  981. focused.EnsureFocus ();
  982. // Send focus upwards
  983. SuperView?.SetFocus (this);
  984. }
  985. /// <summary>
  986. /// Defines the event arguments for <see cref="KeyEvent"/>
  987. /// </summary>
  988. public class KeyEventEventArgs : EventArgs {
  989. /// <summary>
  990. /// Constructs.
  991. /// </summary>
  992. /// <param name="ke"></param>
  993. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  994. /// <summary>
  995. /// The <see cref="KeyEvent"/> for the event.
  996. /// </summary>
  997. public KeyEvent KeyEvent { get; set; }
  998. /// <summary>
  999. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1000. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1001. /// </summary>
  1002. public bool Handled { get; set; } = false;
  1003. }
  1004. /// <summary>
  1005. /// Invoked when a character key is pressed and occurs after the key up event.
  1006. /// </summary>
  1007. public Action<KeyEventEventArgs> KeyPress;
  1008. /// <inheritdoc/>
  1009. public override bool ProcessKey (KeyEvent keyEvent)
  1010. {
  1011. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1012. KeyPress?.Invoke (args);
  1013. if (args.Handled)
  1014. return true;
  1015. if (Focused?.ProcessKey (keyEvent) == true)
  1016. return true;
  1017. return false;
  1018. }
  1019. /// <inheritdoc/>
  1020. public override bool ProcessHotKey (KeyEvent keyEvent)
  1021. {
  1022. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1023. KeyPress?.Invoke (args);
  1024. if (args.Handled)
  1025. return true;
  1026. if (subviews == null || subviews.Count == 0)
  1027. return false;
  1028. foreach (var view in subviews)
  1029. if (view.SuperView.IsCurrentTop && view.ProcessHotKey (keyEvent))
  1030. return true;
  1031. return false;
  1032. }
  1033. /// <inheritdoc/>
  1034. public override bool ProcessColdKey (KeyEvent keyEvent)
  1035. {
  1036. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1037. KeyPress?.Invoke (args);
  1038. if (args.Handled)
  1039. return true;
  1040. if (subviews == null || subviews.Count == 0)
  1041. return false;
  1042. foreach (var view in subviews)
  1043. if (view.SuperView.IsCurrentTop && view.ProcessColdKey (keyEvent))
  1044. return true;
  1045. return false;
  1046. }
  1047. /// <summary>
  1048. /// Invoked when a key is pressed
  1049. /// </summary>
  1050. public Action<KeyEventEventArgs> KeyDown;
  1051. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1052. public override bool OnKeyDown (KeyEvent keyEvent)
  1053. {
  1054. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1055. KeyDown?.Invoke (args);
  1056. if (args.Handled)
  1057. return true;
  1058. if (subviews == null || subviews.Count == 0)
  1059. return false;
  1060. foreach (var view in subviews)
  1061. if (view.SuperView.IsCurrentTop && view.OnKeyDown (keyEvent))
  1062. return true;
  1063. return false;
  1064. }
  1065. /// <summary>
  1066. /// Invoked when a key is released
  1067. /// </summary>
  1068. public Action<KeyEventEventArgs> KeyUp;
  1069. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1070. public override bool OnKeyUp (KeyEvent keyEvent)
  1071. {
  1072. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1073. KeyUp?.Invoke (args);
  1074. if (args.Handled)
  1075. return true;
  1076. if (subviews == null || subviews.Count == 0)
  1077. return false;
  1078. foreach (var view in subviews)
  1079. if (view.SuperView.IsCurrentTop && view.OnKeyUp (keyEvent))
  1080. return true;
  1081. return false;
  1082. }
  1083. /// <summary>
  1084. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1085. /// </summary>
  1086. public void EnsureFocus ()
  1087. {
  1088. if (focused == null)
  1089. if (FocusDirection == Direction.Forward)
  1090. FocusFirst ();
  1091. else
  1092. FocusLast ();
  1093. }
  1094. /// <summary>
  1095. /// Focuses the first focusable subview if one exists.
  1096. /// </summary>
  1097. public void FocusFirst ()
  1098. {
  1099. if (subviews == null) {
  1100. SuperView?.SetFocus (this);
  1101. return;
  1102. }
  1103. foreach (var view in subviews) {
  1104. if (view.CanFocus) {
  1105. SetFocus (view);
  1106. return;
  1107. }
  1108. }
  1109. }
  1110. /// <summary>
  1111. /// Focuses the last focusable subview if one exists.
  1112. /// </summary>
  1113. public void FocusLast ()
  1114. {
  1115. if (subviews == null) {
  1116. SuperView?.SetFocus (this);
  1117. return;
  1118. }
  1119. for (int i = subviews.Count; i > 0;) {
  1120. i--;
  1121. View v = subviews [i];
  1122. if (v.CanFocus) {
  1123. SetFocus (v);
  1124. return;
  1125. }
  1126. }
  1127. }
  1128. /// <summary>
  1129. /// Focuses the previous view.
  1130. /// </summary>
  1131. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1132. public bool FocusPrev ()
  1133. {
  1134. FocusDirection = Direction.Backward;
  1135. if (subviews == null || subviews.Count == 0)
  1136. return false;
  1137. if (focused == null) {
  1138. FocusLast ();
  1139. return focused != null;
  1140. }
  1141. int focused_idx = -1;
  1142. for (int i = subviews.Count; i > 0;) {
  1143. i--;
  1144. View w = subviews [i];
  1145. if (w.HasFocus) {
  1146. if (w.FocusPrev ())
  1147. return true;
  1148. focused_idx = i;
  1149. continue;
  1150. }
  1151. if (w.CanFocus && focused_idx != -1) {
  1152. focused.HasFocus = false;
  1153. if (w != null && w.CanFocus)
  1154. w.FocusLast ();
  1155. SetFocus (w);
  1156. return true;
  1157. }
  1158. }
  1159. if (focused != null) {
  1160. focused.HasFocus = false;
  1161. focused = null;
  1162. }
  1163. return false;
  1164. }
  1165. /// <summary>
  1166. /// Focuses the next view.
  1167. /// </summary>
  1168. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1169. public bool FocusNext ()
  1170. {
  1171. FocusDirection = Direction.Forward;
  1172. if (subviews == null || subviews.Count == 0)
  1173. return false;
  1174. if (focused == null) {
  1175. FocusFirst ();
  1176. return focused != null;
  1177. }
  1178. int n = subviews.Count;
  1179. int focused_idx = -1;
  1180. for (int i = 0; i < n; i++) {
  1181. View w = subviews [i];
  1182. if (w.HasFocus) {
  1183. if (w.FocusNext ())
  1184. return true;
  1185. focused_idx = i;
  1186. continue;
  1187. }
  1188. if (w.CanFocus && focused_idx != -1) {
  1189. focused.HasFocus = false;
  1190. if (w != null && w.CanFocus)
  1191. w.FocusFirst ();
  1192. SetFocus (w);
  1193. return true;
  1194. }
  1195. }
  1196. if (focused != null) {
  1197. focused.HasFocus = false;
  1198. focused = null;
  1199. }
  1200. return false;
  1201. }
  1202. /// <summary>
  1203. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1204. /// </summary>
  1205. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1206. /// <remarks>
  1207. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1208. /// </remarks>
  1209. internal void SetRelativeLayout (Rect hostFrame)
  1210. {
  1211. int w, h, _x, _y;
  1212. if (x is Pos.PosCenter) {
  1213. if (width == null)
  1214. w = hostFrame.Width;
  1215. else
  1216. w = width.Anchor (hostFrame.Width);
  1217. _x = x.Anchor (hostFrame.Width - w);
  1218. } else {
  1219. if (x == null)
  1220. _x = 0;
  1221. else
  1222. _x = x.Anchor (hostFrame.Width);
  1223. if (width == null)
  1224. w = hostFrame.Width;
  1225. else if (width is Dim.DimFactor && !((Dim.DimFactor)width).IsFromRemaining ())
  1226. w = width.Anchor (hostFrame.Width);
  1227. else
  1228. w = Math.Max (width.Anchor (hostFrame.Width - _x), 0);
  1229. }
  1230. if (y is Pos.PosCenter) {
  1231. if (height == null)
  1232. h = hostFrame.Height;
  1233. else
  1234. h = height.Anchor (hostFrame.Height);
  1235. _y = y.Anchor (hostFrame.Height - h);
  1236. } else {
  1237. if (y == null)
  1238. _y = 0;
  1239. else
  1240. _y = y.Anchor (hostFrame.Height);
  1241. if (height == null)
  1242. h = hostFrame.Height;
  1243. else if (height is Dim.DimFactor && !((Dim.DimFactor)height).IsFromRemaining ())
  1244. h = height.Anchor (hostFrame.Height);
  1245. else
  1246. h = Math.Max (height.Anchor (hostFrame.Height - _y), 0);
  1247. }
  1248. Frame = new Rect (_x, _y, w, h);
  1249. }
  1250. // https://en.wikipedia.org/wiki/Topological_sorting
  1251. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1252. {
  1253. var result = new List<View> ();
  1254. // Set of all nodes with no incoming edges
  1255. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1256. while (S.Any ()) {
  1257. // remove a node n from S
  1258. var n = S.First ();
  1259. S.Remove (n);
  1260. // add n to tail of L
  1261. if (n != this?.SuperView)
  1262. result.Add (n);
  1263. // for each node m with an edge e from n to m do
  1264. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1265. var m = e.To;
  1266. // remove edge e from the graph
  1267. edges.Remove (e);
  1268. // if m has no other incoming edges then
  1269. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1270. // insert m into S
  1271. S.Add (m);
  1272. }
  1273. }
  1274. }
  1275. if (edges.Any ()) {
  1276. if (!object.ReferenceEquals(edges.First ().From, edges.First ().To)) {
  1277. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {edges.First ().From}. Did you forget to add it to {this}?");
  1278. } else {
  1279. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1280. }
  1281. } else {
  1282. // return L (a topologically sorted order)
  1283. return result;
  1284. }
  1285. }
  1286. /// <summary>
  1287. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1288. /// </summary>
  1289. public class LayoutEventArgs : EventArgs {
  1290. /// <summary>
  1291. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1292. /// </summary>
  1293. public Rect OldBounds { get; set; }
  1294. }
  1295. /// <summary>
  1296. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1297. /// </summary>
  1298. /// <remarks>
  1299. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1300. /// </remarks>
  1301. public Action<LayoutEventArgs> LayoutComplete;
  1302. /// <summary>
  1303. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> after all sub-views have been laid out.
  1304. /// </summary>
  1305. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1306. {
  1307. LayoutComplete?.Invoke (args);
  1308. }
  1309. /// <summary>
  1310. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1311. /// response to the container view or terminal resizing.
  1312. /// </summary>
  1313. /// <remarks>
  1314. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1315. /// </remarks>
  1316. public virtual void LayoutSubviews ()
  1317. {
  1318. if (!layoutNeeded)
  1319. return;
  1320. Rect oldBounds = Bounds;
  1321. // Sort out the dependencies of the X, Y, Width, Height properties
  1322. var nodes = new HashSet<View> ();
  1323. var edges = new HashSet<(View, View)> ();
  1324. foreach (var v in InternalSubviews) {
  1325. nodes.Add (v);
  1326. if (v.LayoutStyle == LayoutStyle.Computed) {
  1327. if (v.X is Pos.PosView vX)
  1328. edges.Add ((vX.Target, v));
  1329. if (v.Y is Pos.PosView vY)
  1330. edges.Add ((vY.Target, v));
  1331. if (v.Width is Dim.DimView vWidth)
  1332. edges.Add ((vWidth.Target, v));
  1333. if (v.Height is Dim.DimView vHeight)
  1334. edges.Add ((vHeight.Target, v));
  1335. }
  1336. }
  1337. var ordered = TopologicalSort (nodes, edges);
  1338. foreach (var v in ordered) {
  1339. if (v.LayoutStyle == LayoutStyle.Computed)
  1340. v.SetRelativeLayout (Frame);
  1341. v.LayoutSubviews ();
  1342. v.layoutNeeded = false;
  1343. }
  1344. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1345. SetRelativeLayout (Frame);
  1346. }
  1347. layoutNeeded = false;
  1348. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1349. }
  1350. /// <summary>
  1351. /// A generic virtual method at the level of View to manipulate any hot-keys.
  1352. /// </summary>
  1353. /// <param name="text">The text to manipulate.</param>
  1354. /// <param name="hotKey">The hot-key to look for.</param>
  1355. /// <param name="hotPos">The returning hot-key position.</param>
  1356. /// <param name="showHotKey">The character immediately to the right relative to the hot-key position</param>
  1357. /// <returns>It aims to facilitate the preparation for <see cref="TextAlignment"/> procedures.</returns>
  1358. public virtual ustring GetTextFromHotKey (ustring text, Rune hotKey, out int hotPos, out Rune showHotKey)
  1359. {
  1360. Rune hot_key = (Rune)0;
  1361. int hot_pos = -1;
  1362. ustring shown_text = text;
  1363. // Use first hot_key char passed into 'hotKey'.
  1364. int i = 0;
  1365. foreach (Rune c in shown_text) {
  1366. if ((char)c != 0xFFFD) {
  1367. if (c == hotKey) {
  1368. hot_pos = i;
  1369. } else if (hot_pos > -1) {
  1370. hot_key = c;
  1371. break;
  1372. }
  1373. }
  1374. i++;
  1375. }
  1376. if (hot_pos == -1) {
  1377. // Use first upper-case char if there are no hot-key in the text.
  1378. i = 0;
  1379. foreach (Rune c in shown_text) {
  1380. if ((char)c != 0xFFFD) {
  1381. if (Rune.IsUpper (c)) {
  1382. hot_key = c;
  1383. hot_pos = i;
  1384. break;
  1385. }
  1386. }
  1387. i++;
  1388. }
  1389. } else {
  1390. // Use char after 'hotKey'
  1391. ustring start = "";
  1392. i = 0;
  1393. foreach (Rune c in shown_text) {
  1394. start += ustring.Make (c);
  1395. i++;
  1396. if (i == hot_pos)
  1397. break;
  1398. }
  1399. var st = shown_text;
  1400. shown_text = start;
  1401. i = 0;
  1402. foreach (Rune c in st) {
  1403. i++;
  1404. if (i > hot_pos + 1) {
  1405. shown_text += ustring.Make (c);
  1406. }
  1407. }
  1408. }
  1409. hotPos = hot_pos;
  1410. showHotKey = hot_key;
  1411. return shown_text;
  1412. }
  1413. /// <summary>
  1414. /// A generic virtual method at the level of View to manipulate any hot-keys with <see cref="TextAlignment"/> process.
  1415. /// </summary>
  1416. /// <param name="shown_text">The text to manipulate to align.</param>
  1417. /// <param name="hot_pos">The passed in hot-key position.</param>
  1418. /// <param name="c_hot_pos">The returning hot-key position.</param>
  1419. /// <param name="textAlignment">The <see cref="TextAlignment"/> to align to.</param>
  1420. /// <returns>It performs the <see cref="TextAlignment"/> process to the caller.</returns>
  1421. public virtual ustring GetTextAlignment (ustring shown_text, int hot_pos, out int c_hot_pos, TextAlignment textAlignment)
  1422. {
  1423. int start;
  1424. var caption = shown_text;
  1425. c_hot_pos = hot_pos;
  1426. if (Frame.Width > shown_text.Length + 1) {
  1427. switch (textAlignment) {
  1428. case TextAlignment.Left:
  1429. caption += new string (' ', Frame.Width - caption.RuneCount);
  1430. break;
  1431. case TextAlignment.Right:
  1432. start = Frame.Width - caption.RuneCount;
  1433. caption = $"{new string (' ', Frame.Width - caption.RuneCount)}{caption}";
  1434. if (c_hot_pos > -1) {
  1435. c_hot_pos += start;
  1436. }
  1437. break;
  1438. case TextAlignment.Centered:
  1439. start = Frame.Width / 2 - caption.RuneCount / 2;
  1440. caption = $"{new string (' ', start)}{caption}{new string (' ', Frame.Width - caption.RuneCount - start)}";
  1441. if (c_hot_pos > -1) {
  1442. c_hot_pos += start;
  1443. }
  1444. break;
  1445. case TextAlignment.Justified:
  1446. var words = caption.Split (" ");
  1447. var wLen = GetWordsLength (words, c_hot_pos, out int runeCount, out int w_hot_pos);
  1448. var space = (Frame.Width - runeCount) / (caption.Length - wLen);
  1449. caption = "";
  1450. for (int i = 0; i < words.Length; i++) {
  1451. if (i == words.Length - 1) {
  1452. caption += new string (' ', Frame.Width - caption.RuneCount - 1);
  1453. caption += words [i];
  1454. } else {
  1455. caption += words [i];
  1456. }
  1457. if (i < words.Length - 1) {
  1458. caption += new string (' ', space);
  1459. }
  1460. }
  1461. if (c_hot_pos > -1) {
  1462. c_hot_pos += w_hot_pos * space - space - w_hot_pos + 1;
  1463. }
  1464. break;
  1465. }
  1466. }
  1467. return caption;
  1468. }
  1469. int GetWordsLength (ustring [] words, int hotPos, out int runeCount, out int wordHotPos)
  1470. {
  1471. int length = 0;
  1472. int rCount = 0;
  1473. int wHotPos = -1;
  1474. for (int i = 0; i < words.Length; i++) {
  1475. if (wHotPos == -1 && rCount + words [i].RuneCount >= hotPos)
  1476. wHotPos = i;
  1477. length += words [i].Length;
  1478. rCount += words [i].RuneCount;
  1479. }
  1480. if (wHotPos == -1 && hotPos > -1)
  1481. wHotPos = words.Length;
  1482. runeCount = rCount;
  1483. wordHotPos = wHotPos;
  1484. return length;
  1485. }
  1486. /// <summary>
  1487. /// Pretty prints the View
  1488. /// </summary>
  1489. /// <returns></returns>
  1490. public override string ToString ()
  1491. {
  1492. return $"{GetType ().Name}({Id})({Frame})";
  1493. }
  1494. /// <summary>
  1495. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1496. /// </summary>
  1497. public class MouseEventArgs : EventArgs {
  1498. /// <summary>
  1499. /// Constructs.
  1500. /// </summary>
  1501. /// <param name="me"></param>
  1502. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  1503. /// <summary>
  1504. /// The <see cref="MouseEvent"/> for the event.
  1505. /// </summary>
  1506. public MouseEvent MouseEvent { get; set; }
  1507. /// <summary>
  1508. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1509. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1510. /// </summary>
  1511. public bool Handled { get; set; }
  1512. }
  1513. /// <inheritdoc/>
  1514. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1515. {
  1516. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1517. MouseEnter?.Invoke (args);
  1518. if (args.Handled)
  1519. return true;
  1520. if (base.OnMouseEnter (mouseEvent))
  1521. return true;
  1522. return false;
  1523. }
  1524. /// <inheritdoc/>
  1525. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1526. {
  1527. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1528. MouseLeave?.Invoke (args);
  1529. if (args.Handled)
  1530. return true;
  1531. if (base.OnMouseLeave (mouseEvent))
  1532. return true;
  1533. return false;
  1534. }
  1535. /// <summary>
  1536. /// Method invoked when a mouse event is generated
  1537. /// </summary>
  1538. /// <param name="mouseEvent"></param>
  1539. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1540. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1541. {
  1542. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1543. MouseClick?.Invoke (args);
  1544. if (args.Handled)
  1545. return true;
  1546. if (MouseEvent (mouseEvent))
  1547. return true;
  1548. return false;
  1549. }
  1550. }
  1551. }