View.cs 52 KB

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