2
0

View.cs 46 KB

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