View.cs 64 KB

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