View.cs 46 KB

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