View.cs 51 KB

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