View.cs 52 KB

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