View.cs 51 KB

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