View.cs 54 KB

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