View.cs 51 KB

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