View.cs 53 KB

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