View.cs 52 KB

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