View.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144
  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 { get; private set; } = 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. /// Removes the <see cref="SetNeedsLayout"/> setting on this view.
  627. /// </summary>
  628. protected void ClearLayoutNeeded ()
  629. {
  630. LayoutNeeded = false;
  631. }
  632. /// <summary>
  633. /// Flags the view-relative region on this View as needing to be repainted.
  634. /// </summary>
  635. /// <param name="region">The view-relative region that must be flagged for repaint.</param>
  636. public void SetNeedsDisplay (Rect region)
  637. {
  638. if (NeedDisplay.IsEmpty)
  639. NeedDisplay = region;
  640. else {
  641. var x = Math.Min (NeedDisplay.X, region.X);
  642. var y = Math.Min (NeedDisplay.Y, region.Y);
  643. var w = Math.Max (NeedDisplay.Width, region.Width);
  644. var h = Math.Max (NeedDisplay.Height, region.Height);
  645. NeedDisplay = new Rect (x, y, w, h);
  646. }
  647. if (container != null)
  648. container.SetChildNeedsDisplay ();
  649. if (subviews == null)
  650. return;
  651. foreach (var view in subviews)
  652. if (view.Frame.IntersectsWith (region)) {
  653. var childRegion = Rect.Intersect (view.Frame, region);
  654. childRegion.X -= view.Frame.X;
  655. childRegion.Y -= view.Frame.Y;
  656. view.SetNeedsDisplay (childRegion);
  657. }
  658. }
  659. internal bool ChildNeedsDisplay { get; private set; }
  660. /// <summary>
  661. /// Indicates that any child views (in the <see cref="Subviews"/> list) need to be repainted.
  662. /// </summary>
  663. public void SetChildNeedsDisplay ()
  664. {
  665. ChildNeedsDisplay = true;
  666. if (container != null)
  667. container.SetChildNeedsDisplay ();
  668. }
  669. internal bool addingView = false;
  670. /// <summary>
  671. /// Adds a subview (child) to this view.
  672. /// </summary>
  673. /// <remarks>
  674. /// 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"/>
  675. /// </remarks>
  676. public virtual void Add (View view)
  677. {
  678. if (view == null)
  679. return;
  680. if (subviews == null) {
  681. subviews = new List<View> ();
  682. }
  683. if (tabIndexes == null) {
  684. tabIndexes = new List<View> ();
  685. }
  686. subviews.Add (view);
  687. tabIndexes.Add (view);
  688. view.container = this;
  689. if (view.CanFocus) {
  690. addingView = true;
  691. if (SuperView?.CanFocus == false) {
  692. SuperView.addingView = true;
  693. SuperView.CanFocus = true;
  694. SuperView.addingView = false;
  695. }
  696. CanFocus = true;
  697. view.tabIndex = tabIndexes.IndexOf (view);
  698. addingView = false;
  699. }
  700. SetNeedsLayout ();
  701. SetNeedsDisplay ();
  702. OnAdded (view);
  703. if (IsInitialized) {
  704. view.BeginInit ();
  705. view.EndInit ();
  706. }
  707. }
  708. /// <summary>
  709. /// Adds the specified views (children) to the view.
  710. /// </summary>
  711. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  712. /// <remarks>
  713. /// 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"/>
  714. /// </remarks>
  715. public void Add (params View [] views)
  716. {
  717. if (views == null)
  718. return;
  719. foreach (var view in views)
  720. Add (view);
  721. }
  722. /// <summary>
  723. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  724. /// </summary>
  725. public virtual void RemoveAll ()
  726. {
  727. if (subviews == null)
  728. return;
  729. while (subviews.Count > 0) {
  730. Remove (subviews [0]);
  731. }
  732. }
  733. /// <summary>
  734. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  735. /// </summary>
  736. /// <remarks>
  737. /// </remarks>
  738. public virtual void Remove (View view)
  739. {
  740. if (view == null || subviews == null)
  741. return;
  742. SetNeedsLayout ();
  743. SetNeedsDisplay ();
  744. var touched = view.Frame;
  745. subviews.Remove (view);
  746. tabIndexes.Remove (view);
  747. view.container = null;
  748. view.tabIndex = -1;
  749. if (subviews.Count < 1) {
  750. CanFocus = false;
  751. }
  752. foreach (var v in subviews) {
  753. if (v.Frame.IntersectsWith (touched))
  754. view.SetNeedsDisplay ();
  755. }
  756. OnRemoved (view);
  757. if (focused == view) {
  758. focused = null;
  759. }
  760. }
  761. void PerformActionForSubview (View subview, Action<View> action)
  762. {
  763. if (subviews.Contains (subview)) {
  764. action (subview);
  765. }
  766. SetNeedsDisplay ();
  767. subview.SetNeedsDisplay ();
  768. }
  769. /// <summary>
  770. /// Brings the specified subview to the front so it is drawn on top of any other views.
  771. /// </summary>
  772. /// <param name="subview">The subview to send to the front</param>
  773. /// <remarks>
  774. /// <seealso cref="SendSubviewToBack"/>.
  775. /// </remarks>
  776. public void BringSubviewToFront (View subview)
  777. {
  778. PerformActionForSubview (subview, x => {
  779. subviews.Remove (x);
  780. subviews.Add (x);
  781. });
  782. }
  783. /// <summary>
  784. /// Sends the specified subview to the front so it is the first view drawn
  785. /// </summary>
  786. /// <param name="subview">The subview to send to the front</param>
  787. /// <remarks>
  788. /// <seealso cref="BringSubviewToFront(View)"/>.
  789. /// </remarks>
  790. public void SendSubviewToBack (View subview)
  791. {
  792. PerformActionForSubview (subview, x => {
  793. subviews.Remove (x);
  794. subviews.Insert (0, subview);
  795. });
  796. }
  797. /// <summary>
  798. /// Moves the subview backwards in the hierarchy, only one step
  799. /// </summary>
  800. /// <param name="subview">The subview to send backwards</param>
  801. /// <remarks>
  802. /// If you want to send the view all the way to the back use SendSubviewToBack.
  803. /// </remarks>
  804. public void SendSubviewBackwards (View subview)
  805. {
  806. PerformActionForSubview (subview, x => {
  807. var idx = subviews.IndexOf (x);
  808. if (idx > 0) {
  809. subviews.Remove (x);
  810. subviews.Insert (idx - 1, x);
  811. }
  812. });
  813. }
  814. /// <summary>
  815. /// Moves the subview backwards in the hierarchy, only one step
  816. /// </summary>
  817. /// <param name="subview">The subview to send backwards</param>
  818. /// <remarks>
  819. /// If you want to send the view all the way to the back use SendSubviewToBack.
  820. /// </remarks>
  821. public void BringSubviewForward (View subview)
  822. {
  823. PerformActionForSubview (subview, x => {
  824. var idx = subviews.IndexOf (x);
  825. if (idx + 1 < subviews.Count) {
  826. subviews.Remove (x);
  827. subviews.Insert (idx + 1, x);
  828. }
  829. });
  830. }
  831. /// <summary>
  832. /// Clears the view region with the current color.
  833. /// </summary>
  834. /// <remarks>
  835. /// <para>
  836. /// This clears the entire region used by this view.
  837. /// </para>
  838. /// </remarks>
  839. public void Clear ()
  840. {
  841. var h = Frame.Height;
  842. var w = Frame.Width;
  843. for (int line = 0; line < h; line++) {
  844. Move (0, line);
  845. for (int col = 0; col < w; col++)
  846. Driver.AddRune (' ');
  847. }
  848. }
  849. /// <summary>
  850. /// Clears the specified region with the current color.
  851. /// </summary>
  852. /// <remarks>
  853. /// </remarks>
  854. /// <param name="regionScreen">The screen-relative region to clear.</param>
  855. public void Clear (Rect regionScreen)
  856. {
  857. var h = regionScreen.Height;
  858. var w = regionScreen.Width;
  859. for (int line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  860. Driver.Move (regionScreen.X, line);
  861. for (int col = 0; col < w; col++)
  862. Driver.AddRune (' ');
  863. }
  864. }
  865. /// <summary>
  866. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  867. /// </summary>
  868. /// <param name="col">View-relative column.</param>
  869. /// <param name="row">View-relative row.</param>
  870. /// <param name="rcol">Absolute column; screen-relative.</param>
  871. /// <param name="rrow">Absolute row; screen-relative.</param>
  872. /// <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>
  873. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  874. {
  875. // Computes the real row, col relative to the screen.
  876. rrow = row + frame.Y;
  877. rcol = col + frame.X;
  878. var ccontainer = container;
  879. while (ccontainer != null) {
  880. rrow += ccontainer.frame.Y;
  881. rcol += ccontainer.frame.X;
  882. ccontainer = ccontainer.container;
  883. }
  884. // The following ensures that the cursor is always in the screen boundaries.
  885. if (clipped) {
  886. rrow = Math.Min (rrow, Driver.Rows - 1);
  887. rcol = Math.Min (rcol, Driver.Cols - 1);
  888. }
  889. }
  890. /// <summary>
  891. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  892. /// </summary>
  893. /// <returns>The mapped point.</returns>
  894. /// <param name="x">X screen-coordinate point.</param>
  895. /// <param name="y">Y screen-coordinate point.</param>
  896. public Point ScreenToView (int x, int y)
  897. {
  898. if (SuperView == null) {
  899. return new Point (x - Frame.X, y - frame.Y);
  900. } else {
  901. var parent = SuperView.ScreenToView (x, y);
  902. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  903. }
  904. }
  905. /// <summary>
  906. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  907. /// </summary>
  908. internal Rect ViewToScreen (Rect region)
  909. {
  910. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  911. return new Rect (x, y, region.Width, region.Height);
  912. }
  913. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  914. internal Rect ScreenClip (Rect regionScreen)
  915. {
  916. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  917. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  918. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  919. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  920. return new Rect (x, y, w, h);
  921. }
  922. /// <summary>
  923. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  924. /// </summary>
  925. /// <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>
  926. /// <remarks>
  927. /// <see cref="Bounds"/> is View-relative.
  928. /// </remarks>
  929. public Rect ClipToBounds ()
  930. {
  931. return SetClip (Bounds);
  932. }
  933. /// <summary>
  934. /// Sets the clip region to the specified view-relative region.
  935. /// </summary>
  936. /// <returns>The previous screen-relative clip region.</returns>
  937. /// <param name="region">View-relative clip region.</param>
  938. public Rect SetClip (Rect region)
  939. {
  940. var previous = Driver.Clip;
  941. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  942. return previous;
  943. }
  944. /// <summary>
  945. /// Draws a frame in the current view, clipped by the boundary of this view
  946. /// </summary>
  947. /// <param name="region">View-relative region for the frame to be drawn.</param>
  948. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  949. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  950. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  951. {
  952. var scrRect = ViewToScreen (region);
  953. var savedClip = ClipToBounds ();
  954. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  955. Driver.Clip = savedClip;
  956. }
  957. /// <summary>
  958. /// Utility function to draw strings that contain a hotkey.
  959. /// </summary>
  960. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  961. /// <param name="hotColor">Hot color.</param>
  962. /// <param name="normalColor">Normal color.</param>
  963. /// <remarks>
  964. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  965. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  966. /// </remarks>
  967. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  968. {
  969. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  970. Application.Driver.SetAttribute (normalColor);
  971. foreach (var rune in text) {
  972. if (rune == hotkeySpec) {
  973. Application.Driver.SetAttribute (hotColor);
  974. continue;
  975. }
  976. Application.Driver.AddRune (rune);
  977. Application.Driver.SetAttribute (normalColor);
  978. }
  979. }
  980. /// <summary>
  981. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  982. /// </summary>
  983. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  984. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  985. /// <param name="scheme">The color scheme to use.</param>
  986. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  987. {
  988. if (focused)
  989. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  990. else
  991. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  992. }
  993. /// <summary>
  994. /// This moves the cursor to the specified column and row in the view.
  995. /// </summary>
  996. /// <returns>The move.</returns>
  997. /// <param name="col">Col.</param>
  998. /// <param name="row">Row.</param>
  999. public void Move (int col, int row)
  1000. {
  1001. if (Driver.Rows == 0) {
  1002. return;
  1003. }
  1004. ViewToScreen (col, row, out var rcol, out var rrow);
  1005. Driver.Move (rcol, rrow);
  1006. }
  1007. /// <summary>
  1008. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1009. /// </summary>
  1010. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1011. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1012. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1013. /// the last focused view. Views should make sure that they place the cursor
  1014. /// in a visually sensible place.
  1015. public virtual void PositionCursor ()
  1016. {
  1017. if (!CanBeVisible (this)) {
  1018. return;
  1019. }
  1020. if (focused != null) {
  1021. focused.PositionCursor ();
  1022. } else {
  1023. if (CanFocus && HasFocus && Visible) {
  1024. Move (textFormatter.HotKeyPos == -1 ? 0 : textFormatter.CursorPosition, 0);
  1025. } else {
  1026. Move (frame.X, frame.Y);
  1027. }
  1028. }
  1029. }
  1030. bool hasFocus;
  1031. /// <inheritdoc/>
  1032. public override bool HasFocus {
  1033. get {
  1034. return hasFocus;
  1035. }
  1036. }
  1037. void SetHasFocus (bool value, View view)
  1038. {
  1039. if (hasFocus != value) {
  1040. hasFocus = value;
  1041. if (value) {
  1042. OnEnter (view);
  1043. } else {
  1044. OnLeave (view);
  1045. }
  1046. SetNeedsDisplay ();
  1047. }
  1048. // Remove focus down the chain of subviews if focus is removed
  1049. if (!value && focused != null) {
  1050. focused.OnLeave (view);
  1051. focused.SetHasFocus (false, view);
  1052. focused = null;
  1053. }
  1054. }
  1055. /// <summary>
  1056. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  1057. /// </summary>
  1058. public class FocusEventArgs : EventArgs {
  1059. /// <summary>
  1060. /// Constructs.
  1061. /// </summary>
  1062. /// <param name="view">The view that gets or loses focus.</param>
  1063. public FocusEventArgs (View view) { View = view; }
  1064. /// <summary>
  1065. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  1066. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1067. /// </summary>
  1068. public bool Handled { get; set; }
  1069. /// <summary>
  1070. /// Indicates the current view that gets or loses focus.
  1071. /// </summary>
  1072. public View View { get; set; }
  1073. }
  1074. /// <summary>
  1075. /// Method invoked when a subview is being added to this view.
  1076. /// </summary>
  1077. /// <param name="view">The subview being added.</param>
  1078. public virtual void OnAdded (View view)
  1079. {
  1080. view.Added?.Invoke (this);
  1081. }
  1082. /// <summary>
  1083. /// Method invoked when a subview is being removed from this view.
  1084. /// </summary>
  1085. /// <param name="view">The subview being removed.</param>
  1086. public virtual void OnRemoved (View view)
  1087. {
  1088. view.Removed?.Invoke (this);
  1089. }
  1090. /// <inheritdoc/>
  1091. public override bool OnEnter (View view)
  1092. {
  1093. FocusEventArgs args = new FocusEventArgs (view);
  1094. Enter?.Invoke (args);
  1095. if (args.Handled)
  1096. return true;
  1097. if (base.OnEnter (view))
  1098. return true;
  1099. return false;
  1100. }
  1101. /// <inheritdoc/>
  1102. public override bool OnLeave (View view)
  1103. {
  1104. FocusEventArgs args = new FocusEventArgs (view);
  1105. Leave?.Invoke (args);
  1106. if (args.Handled)
  1107. return true;
  1108. if (base.OnLeave (view))
  1109. return true;
  1110. return false;
  1111. }
  1112. /// <summary>
  1113. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1114. /// </summary>
  1115. /// <value>The focused.</value>
  1116. public View Focused => focused;
  1117. /// <summary>
  1118. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1119. /// </summary>
  1120. /// <value>The most focused.</value>
  1121. public View MostFocused {
  1122. get {
  1123. if (Focused == null)
  1124. return null;
  1125. var most = Focused.MostFocused;
  1126. if (most != null)
  1127. return most;
  1128. return Focused;
  1129. }
  1130. }
  1131. /// <summary>
  1132. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1133. /// color scheme.
  1134. /// </summary>
  1135. public ColorScheme ColorScheme {
  1136. get {
  1137. if (colorScheme == null)
  1138. return SuperView?.ColorScheme;
  1139. return colorScheme;
  1140. }
  1141. set {
  1142. colorScheme = value;
  1143. }
  1144. }
  1145. ColorScheme colorScheme;
  1146. /// <summary>
  1147. /// Displays the specified character in the specified column and row of the View.
  1148. /// </summary>
  1149. /// <param name="col">Column (view-relative).</param>
  1150. /// <param name="row">Row (view-relative).</param>
  1151. /// <param name="ch">Ch.</param>
  1152. public void AddRune (int col, int row, Rune ch)
  1153. {
  1154. if (row < 0 || col < 0)
  1155. return;
  1156. if (row > frame.Height - 1 || col > frame.Width - 1)
  1157. return;
  1158. Move (col, row);
  1159. Driver.AddRune (ch);
  1160. }
  1161. /// <summary>
  1162. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  1163. /// </summary>
  1164. protected void ClearNeedsDisplay ()
  1165. {
  1166. NeedDisplay = Rect.Empty;
  1167. ChildNeedsDisplay = false;
  1168. }
  1169. /// <summary>
  1170. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1171. /// </summary>
  1172. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1173. /// <remarks>
  1174. /// <para>
  1175. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1176. /// </para>
  1177. /// <para>
  1178. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1179. /// the last color that was set globally on the driver.
  1180. /// </para>
  1181. /// <para>
  1182. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1183. /// larger than the <c>region</c> parameter.
  1184. /// </para>
  1185. /// </remarks>
  1186. public virtual void Redraw (Rect bounds)
  1187. {
  1188. if (!CanBeVisible (this)) {
  1189. return;
  1190. }
  1191. var clipRect = new Rect (Point.Empty, frame.Size);
  1192. if (ColorScheme != null)
  1193. Driver.SetAttribute (HasFocus ? ColorScheme.Focus : ColorScheme.Normal);
  1194. if (!ustring.IsNullOrEmpty (Text)) {
  1195. Clear ();
  1196. // Draw any Text
  1197. if (textFormatter != null) {
  1198. textFormatter.NeedsFormat = true;
  1199. }
  1200. textFormatter?.Draw (ViewToScreen (Bounds), HasFocus ? ColorScheme.Focus : ColorScheme.Normal, HasFocus ? ColorScheme.HotFocus : ColorScheme.HotNormal);
  1201. }
  1202. // Invoke DrawContentEvent
  1203. OnDrawContent (bounds);
  1204. if (subviews != null) {
  1205. foreach (var view in subviews) {
  1206. if (!view.NeedDisplay.IsEmpty || view.ChildNeedsDisplay) {
  1207. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1208. if (view.LayoutNeeded)
  1209. view.LayoutSubviews ();
  1210. Application.CurrentView = view;
  1211. // Draw the subview
  1212. // Use the view's bounds (view-relative; Location will always be (0,0) because
  1213. if (view.Visible) {
  1214. view.Redraw (view.Bounds);
  1215. }
  1216. }
  1217. view.NeedDisplay = Rect.Empty;
  1218. view.ChildNeedsDisplay = false;
  1219. }
  1220. }
  1221. }
  1222. ClearNeedsDisplay ();
  1223. }
  1224. /// <summary>
  1225. /// Event invoked when the content area of the View is to be drawn.
  1226. /// </summary>
  1227. /// <remarks>
  1228. /// <para>
  1229. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1230. /// </para>
  1231. /// <para>
  1232. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1233. /// </para>
  1234. /// </remarks>
  1235. public event Action<Rect> DrawContent;
  1236. /// <summary>
  1237. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1238. /// </summary>
  1239. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1240. /// <remarks>
  1241. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1242. /// </remarks>
  1243. public virtual void OnDrawContent (Rect viewport)
  1244. {
  1245. DrawContent?.Invoke (viewport);
  1246. }
  1247. /// <summary>
  1248. /// Causes the specified subview to have focus.
  1249. /// </summary>
  1250. /// <param name="view">View.</param>
  1251. void SetFocus (View view)
  1252. {
  1253. if (view == null)
  1254. return;
  1255. //Console.WriteLine ($"Request to focus {view}");
  1256. if (!view.CanFocus || !view.Visible)
  1257. return;
  1258. if (focused?.hasFocus == true && focused == view)
  1259. return;
  1260. // Make sure that this view is a subview
  1261. View c;
  1262. for (c = view.container; c != null; c = c.container)
  1263. if (c == this)
  1264. break;
  1265. if (c == null)
  1266. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1267. if (focused != null)
  1268. focused.SetHasFocus (false, view);
  1269. var f = focused;
  1270. focused = view;
  1271. focused.SetHasFocus (true, f);
  1272. focused.EnsureFocus ();
  1273. // Send focus upwards
  1274. SuperView?.SetFocus (this);
  1275. }
  1276. /// <summary>
  1277. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  1278. /// </summary>
  1279. public void SetFocus ()
  1280. {
  1281. if (!CanBeVisible (this)) {
  1282. return;
  1283. }
  1284. SuperView?.SetFocus (this);
  1285. }
  1286. /// <summary>
  1287. /// Defines the event arguments for <see cref="KeyEvent"/>
  1288. /// </summary>
  1289. public class KeyEventEventArgs : EventArgs {
  1290. /// <summary>
  1291. /// Constructs.
  1292. /// </summary>
  1293. /// <param name="ke"></param>
  1294. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  1295. /// <summary>
  1296. /// The <see cref="KeyEvent"/> for the event.
  1297. /// </summary>
  1298. public KeyEvent KeyEvent { get; set; }
  1299. /// <summary>
  1300. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1301. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1302. /// </summary>
  1303. public bool Handled { get; set; } = false;
  1304. }
  1305. /// <summary>
  1306. /// Invoked when a character key is pressed and occurs after the key up event.
  1307. /// </summary>
  1308. public event Action<KeyEventEventArgs> KeyPress;
  1309. /// <inheritdoc/>
  1310. public override bool ProcessKey (KeyEvent keyEvent)
  1311. {
  1312. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1313. KeyPress?.Invoke (args);
  1314. if (args.Handled)
  1315. return true;
  1316. if (Focused?.ProcessKey (keyEvent) == true)
  1317. return true;
  1318. return false;
  1319. }
  1320. /// <inheritdoc/>
  1321. public override bool ProcessHotKey (KeyEvent keyEvent)
  1322. {
  1323. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1324. KeyPress?.Invoke (args);
  1325. if (args.Handled)
  1326. return true;
  1327. if (subviews == null || subviews.Count == 0)
  1328. return false;
  1329. foreach (var view in subviews)
  1330. if (view.ProcessHotKey (keyEvent))
  1331. return true;
  1332. return false;
  1333. }
  1334. /// <inheritdoc/>
  1335. public override bool ProcessColdKey (KeyEvent keyEvent)
  1336. {
  1337. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1338. KeyPress?.Invoke (args);
  1339. if (args.Handled)
  1340. return true;
  1341. if (subviews == null || subviews.Count == 0)
  1342. return false;
  1343. foreach (var view in subviews)
  1344. if (view.ProcessColdKey (keyEvent))
  1345. return true;
  1346. return false;
  1347. }
  1348. /// <summary>
  1349. /// Invoked when a key is pressed
  1350. /// </summary>
  1351. public event Action<KeyEventEventArgs> KeyDown;
  1352. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1353. public override bool OnKeyDown (KeyEvent keyEvent)
  1354. {
  1355. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1356. KeyDown?.Invoke (args);
  1357. if (args.Handled) {
  1358. return true;
  1359. }
  1360. if (Focused?.OnKeyDown (keyEvent) == true) {
  1361. return true;
  1362. }
  1363. return false;
  1364. }
  1365. /// <summary>
  1366. /// Invoked when a key is released
  1367. /// </summary>
  1368. public event Action<KeyEventEventArgs> KeyUp;
  1369. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1370. public override bool OnKeyUp (KeyEvent keyEvent)
  1371. {
  1372. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1373. KeyUp?.Invoke (args);
  1374. if (args.Handled) {
  1375. return true;
  1376. }
  1377. if (Focused?.OnKeyUp (keyEvent) == true) {
  1378. return true;
  1379. }
  1380. return false;
  1381. }
  1382. /// <summary>
  1383. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1384. /// </summary>
  1385. public void EnsureFocus ()
  1386. {
  1387. if (focused == null && subviews?.Count > 0) {
  1388. if (FocusDirection == Direction.Forward) {
  1389. FocusFirst ();
  1390. } else {
  1391. FocusLast ();
  1392. }
  1393. }
  1394. }
  1395. /// <summary>
  1396. /// Focuses the first focusable subview if one exists.
  1397. /// </summary>
  1398. public void FocusFirst ()
  1399. {
  1400. if (!CanBeVisible (this)) {
  1401. return;
  1402. }
  1403. if (tabIndexes == null) {
  1404. SuperView?.SetFocus (this);
  1405. return;
  1406. }
  1407. foreach (var view in tabIndexes) {
  1408. if (view.CanFocus && view.tabStop && view.Visible) {
  1409. SetFocus (view);
  1410. return;
  1411. }
  1412. }
  1413. }
  1414. /// <summary>
  1415. /// Focuses the last focusable subview if one exists.
  1416. /// </summary>
  1417. public void FocusLast ()
  1418. {
  1419. if (!CanBeVisible (this)) {
  1420. return;
  1421. }
  1422. if (tabIndexes == null) {
  1423. SuperView?.SetFocus (this);
  1424. return;
  1425. }
  1426. for (int i = tabIndexes.Count; i > 0;) {
  1427. i--;
  1428. View v = tabIndexes [i];
  1429. if (v.CanFocus && v.tabStop && v.Visible) {
  1430. SetFocus (v);
  1431. return;
  1432. }
  1433. }
  1434. }
  1435. /// <summary>
  1436. /// Focuses the previous view.
  1437. /// </summary>
  1438. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1439. public bool FocusPrev ()
  1440. {
  1441. if (!CanBeVisible (this)) {
  1442. return false;
  1443. }
  1444. FocusDirection = Direction.Backward;
  1445. if (tabIndexes == null || tabIndexes.Count == 0)
  1446. return false;
  1447. if (focused == null) {
  1448. FocusLast ();
  1449. return focused != null;
  1450. }
  1451. int focused_idx = -1;
  1452. for (int i = tabIndexes.Count; i > 0;) {
  1453. i--;
  1454. View w = tabIndexes [i];
  1455. if (w.HasFocus) {
  1456. if (w.FocusPrev ())
  1457. return true;
  1458. focused_idx = i;
  1459. continue;
  1460. }
  1461. if (w.CanFocus && focused_idx != -1 && w.tabStop && w.Visible) {
  1462. focused.SetHasFocus (false, w);
  1463. if (w != null && w.CanFocus && w.tabStop && w.Visible)
  1464. w.FocusLast ();
  1465. SetFocus (w);
  1466. return true;
  1467. }
  1468. }
  1469. if (focused != null) {
  1470. focused.SetHasFocus (false, this);
  1471. focused = null;
  1472. }
  1473. return false;
  1474. }
  1475. /// <summary>
  1476. /// Focuses the next view.
  1477. /// </summary>
  1478. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1479. public bool FocusNext ()
  1480. {
  1481. if (!CanBeVisible (this)) {
  1482. return false;
  1483. }
  1484. FocusDirection = Direction.Forward;
  1485. if (tabIndexes == null || tabIndexes.Count == 0)
  1486. return false;
  1487. if (focused == null) {
  1488. FocusFirst ();
  1489. return focused != null;
  1490. }
  1491. int n = tabIndexes.Count;
  1492. int focused_idx = -1;
  1493. for (int i = 0; i < n; i++) {
  1494. View w = tabIndexes [i];
  1495. if (w.HasFocus) {
  1496. if (w.FocusNext ())
  1497. return true;
  1498. focused_idx = i;
  1499. continue;
  1500. }
  1501. if (w.CanFocus && focused_idx != -1 && w.tabStop && w.Visible) {
  1502. focused.SetHasFocus (false, w);
  1503. if (w != null && w.CanFocus && w.tabStop && w.Visible)
  1504. w.FocusFirst ();
  1505. SetFocus (w);
  1506. return true;
  1507. }
  1508. }
  1509. if (focused != null) {
  1510. focused.SetHasFocus (false, this);
  1511. focused = null;
  1512. }
  1513. return false;
  1514. }
  1515. /// <summary>
  1516. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1517. /// </summary>
  1518. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1519. /// <remarks>
  1520. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1521. /// </remarks>
  1522. internal void SetRelativeLayout (Rect hostFrame)
  1523. {
  1524. int w, h, _x, _y;
  1525. if (x is Pos.PosCenter) {
  1526. if (width == null)
  1527. w = hostFrame.Width;
  1528. else
  1529. w = width.Anchor (hostFrame.Width);
  1530. _x = x.Anchor (hostFrame.Width - w);
  1531. } else {
  1532. if (x == null)
  1533. _x = 0;
  1534. else
  1535. _x = x.Anchor (hostFrame.Width);
  1536. if (width == null)
  1537. w = hostFrame.Width;
  1538. else if (width is Dim.DimFactor && !((Dim.DimFactor)width).IsFromRemaining ())
  1539. w = width.Anchor (hostFrame.Width);
  1540. else
  1541. w = Math.Max (width.Anchor (hostFrame.Width - _x), 0);
  1542. }
  1543. if (y is Pos.PosCenter) {
  1544. if (height == null)
  1545. h = hostFrame.Height;
  1546. else
  1547. h = height.Anchor (hostFrame.Height);
  1548. _y = y.Anchor (hostFrame.Height - h);
  1549. } else {
  1550. if (y == null)
  1551. _y = 0;
  1552. else
  1553. _y = y.Anchor (hostFrame.Height);
  1554. if (height == null)
  1555. h = hostFrame.Height;
  1556. else if (height is Dim.DimFactor && !((Dim.DimFactor)height).IsFromRemaining ())
  1557. h = height.Anchor (hostFrame.Height);
  1558. else
  1559. h = Math.Max (height.Anchor (hostFrame.Height - _y), 0);
  1560. }
  1561. var r = new Rect (_x, _y, w, h);
  1562. if (Frame != r) {
  1563. Frame = new Rect (_x, _y, w, h);
  1564. }
  1565. }
  1566. // https://en.wikipedia.org/wiki/Topological_sorting
  1567. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1568. {
  1569. var result = new List<View> ();
  1570. // Set of all nodes with no incoming edges
  1571. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1572. while (S.Any ()) {
  1573. // remove a node n from S
  1574. var n = S.First ();
  1575. S.Remove (n);
  1576. // add n to tail of L
  1577. if (n != this?.SuperView)
  1578. result.Add (n);
  1579. // for each node m with an edge e from n to m do
  1580. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1581. var m = e.To;
  1582. // remove edge e from the graph
  1583. edges.Remove (e);
  1584. // if m has no other incoming edges then
  1585. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1586. // insert m into S
  1587. S.Add (m);
  1588. }
  1589. }
  1590. }
  1591. if (edges.Any ()) {
  1592. if (!object.ReferenceEquals (edges.First ().From, edges.First ().To)) {
  1593. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {edges.First ().From}. Did you forget to add it to {this}?");
  1594. } else {
  1595. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1596. }
  1597. } else {
  1598. // return L (a topologically sorted order)
  1599. return result;
  1600. }
  1601. }
  1602. /// <summary>
  1603. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1604. /// </summary>
  1605. public class LayoutEventArgs : EventArgs {
  1606. /// <summary>
  1607. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1608. /// </summary>
  1609. public Rect OldBounds { get; set; }
  1610. }
  1611. /// <summary>
  1612. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1613. /// </summary>
  1614. /// <remarks>
  1615. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1616. /// </remarks>
  1617. public event Action<LayoutEventArgs> LayoutStarted;
  1618. /// <summary>
  1619. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  1620. /// </summary>
  1621. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  1622. {
  1623. LayoutStarted?.Invoke (args);
  1624. }
  1625. /// <summary>
  1626. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1627. /// </summary>
  1628. /// <remarks>
  1629. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1630. /// </remarks>
  1631. public event Action<LayoutEventArgs> LayoutComplete;
  1632. /// <summary>
  1633. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  1634. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  1635. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  1636. /// </summary>
  1637. public event EventHandler Initialized;
  1638. /// <summary>
  1639. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  1640. /// </summary>
  1641. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1642. {
  1643. LayoutComplete?.Invoke (args);
  1644. }
  1645. /// <summary>
  1646. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1647. /// response to the container view or terminal resizing.
  1648. /// </summary>
  1649. /// <remarks>
  1650. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1651. /// </remarks>
  1652. public virtual void LayoutSubviews ()
  1653. {
  1654. if (!LayoutNeeded) {
  1655. return;
  1656. }
  1657. Rect oldBounds = Bounds;
  1658. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  1659. textFormatter.Size = Bounds.Size;
  1660. // Sort out the dependencies of the X, Y, Width, Height properties
  1661. var nodes = new HashSet<View> ();
  1662. var edges = new HashSet<(View, View)> ();
  1663. foreach (var v in InternalSubviews) {
  1664. nodes.Add (v);
  1665. if (v.LayoutStyle == LayoutStyle.Computed) {
  1666. if (v.X is Pos.PosView vX)
  1667. edges.Add ((vX.Target, v));
  1668. if (v.Y is Pos.PosView vY)
  1669. edges.Add ((vY.Target, v));
  1670. if (v.Width is Dim.DimView vWidth)
  1671. edges.Add ((vWidth.Target, v));
  1672. if (v.Height is Dim.DimView vHeight)
  1673. edges.Add ((vHeight.Target, v));
  1674. }
  1675. }
  1676. var ordered = TopologicalSort (nodes, edges);
  1677. foreach (var v in ordered) {
  1678. if (v.LayoutStyle == LayoutStyle.Computed) {
  1679. v.SetRelativeLayout (Frame);
  1680. }
  1681. v.LayoutSubviews ();
  1682. v.LayoutNeeded = false;
  1683. }
  1684. if (SuperView == Application.Top && LayoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1685. SetRelativeLayout (Frame);
  1686. }
  1687. LayoutNeeded = false;
  1688. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1689. }
  1690. /// <summary>
  1691. /// The text displayed by the <see cref="View"/>.
  1692. /// </summary>
  1693. /// <remarks>
  1694. /// <para>
  1695. /// If provided, the text will be drawn before any subviews are drawn.
  1696. /// </para>
  1697. /// <para>
  1698. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  1699. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  1700. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  1701. /// is 1, the text will be clipped.
  1702. /// </para>
  1703. /// <para>
  1704. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  1705. /// <c>(Rune)0xffff</c>.
  1706. /// </para>
  1707. /// </remarks>
  1708. public virtual ustring Text {
  1709. get => textFormatter.Text;
  1710. set {
  1711. textFormatter.Text = value;
  1712. ResizeView (autoSize);
  1713. SetNeedsLayout ();
  1714. SetNeedsDisplay ();
  1715. }
  1716. }
  1717. /// <summary>
  1718. /// Used by <see cref="Text"/> to resize the view's <see cref="Bounds"/> with the <see cref="TextFormatter.Size"/>.
  1719. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="Width"/> and <see cref="Height"/> are null or
  1720. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  1721. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  1722. /// </summary>
  1723. public virtual bool AutoSize {
  1724. get => autoSize;
  1725. set {
  1726. var v = ResizeView (value);
  1727. if (autoSize != v) {
  1728. autoSize = v;
  1729. SetNeedsLayout ();
  1730. SetNeedsDisplay ();
  1731. }
  1732. }
  1733. }
  1734. /// <summary>
  1735. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  1736. /// </summary>
  1737. /// <value>The text alignment.</value>
  1738. public virtual TextAlignment TextAlignment {
  1739. get => textFormatter.Alignment;
  1740. set {
  1741. textFormatter.Alignment = value;
  1742. SetNeedsDisplay ();
  1743. }
  1744. }
  1745. /// <summary>
  1746. /// Get or sets if the <see cref="View"/> was already initialized.
  1747. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  1748. /// </summary>
  1749. public bool IsInitialized { get; set; }
  1750. /// <summary>
  1751. /// Pretty prints the View
  1752. /// </summary>
  1753. /// <returns></returns>
  1754. public override string ToString ()
  1755. {
  1756. return $"{GetType ().Name}({Id})({Frame})";
  1757. }
  1758. bool ResizeView (bool autoSize)
  1759. {
  1760. if (textFormatter.Size != Bounds.Size && (((width == null || width is Dim.DimAbsolute) && (Bounds.Width == 0
  1761. || autoSize && Bounds.Width != textFormatter.Size.Width))
  1762. || ((height == null || height is Dim.DimAbsolute) && (Bounds.Height == 0
  1763. || autoSize && Bounds.Height != textFormatter.Size.Height)))) {
  1764. Bounds = new Rect (Bounds.X, Bounds.Y, textFormatter.Size.Width, textFormatter.Size.Height);
  1765. if (width == null) {
  1766. width = Bounds.Width;
  1767. } else if (width is Dim.DimAbsolute) {
  1768. width = Math.Max (Bounds.Width, height.Anchor (Bounds.Width));
  1769. } else {
  1770. return false;
  1771. }
  1772. if (height == null) {
  1773. height = Bounds.Height;
  1774. } else if (height is Dim.DimAbsolute) {
  1775. height = Math.Max (Bounds.Height, height.Anchor (Bounds.Height));
  1776. } else {
  1777. return false;
  1778. }
  1779. }
  1780. return autoSize;
  1781. }
  1782. /// <summary>
  1783. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1784. /// </summary>
  1785. public class MouseEventArgs : EventArgs {
  1786. /// <summary>
  1787. /// Constructs.
  1788. /// </summary>
  1789. /// <param name="me"></param>
  1790. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  1791. /// <summary>
  1792. /// The <see cref="MouseEvent"/> for the event.
  1793. /// </summary>
  1794. public MouseEvent MouseEvent { get; set; }
  1795. /// <summary>
  1796. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1797. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1798. /// </summary>
  1799. public bool Handled { get; set; }
  1800. }
  1801. /// <inheritdoc/>
  1802. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1803. {
  1804. if (!CanBeVisible (this)) {
  1805. return false;
  1806. }
  1807. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1808. MouseEnter?.Invoke (args);
  1809. if (args.Handled)
  1810. return true;
  1811. if (base.OnMouseEnter (mouseEvent))
  1812. return true;
  1813. return false;
  1814. }
  1815. /// <inheritdoc/>
  1816. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1817. {
  1818. if (!CanBeVisible (this)) {
  1819. return false;
  1820. }
  1821. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1822. MouseLeave?.Invoke (args);
  1823. if (args.Handled)
  1824. return true;
  1825. if (base.OnMouseLeave (mouseEvent))
  1826. return true;
  1827. return false;
  1828. }
  1829. /// <summary>
  1830. /// Method invoked when a mouse event is generated
  1831. /// </summary>
  1832. /// <param name="mouseEvent"></param>
  1833. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1834. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1835. {
  1836. if (!CanBeVisible (this)) {
  1837. return false;
  1838. }
  1839. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1840. OnMouseClick (args);
  1841. if (args.Handled)
  1842. return true;
  1843. if (MouseEvent (mouseEvent))
  1844. return true;
  1845. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  1846. if (CanFocus && !HasFocus && SuperView != null) {
  1847. SuperView.SetFocus (this);
  1848. SetNeedsDisplay ();
  1849. }
  1850. return true;
  1851. }
  1852. return false;
  1853. }
  1854. /// <summary>
  1855. /// Invokes the MouseClick event.
  1856. /// </summary>
  1857. protected void OnMouseClick (MouseEventArgs args) => MouseClick?.Invoke (args);
  1858. /// <inheritdoc/>
  1859. protected override void Dispose (bool disposing)
  1860. {
  1861. for (int i = InternalSubviews.Count - 1; i >= 0; i--) {
  1862. View subview = InternalSubviews [i];
  1863. Remove (subview);
  1864. subview.Dispose ();
  1865. }
  1866. base.Dispose (disposing);
  1867. }
  1868. /// <summary>
  1869. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are beginning initialized.
  1870. /// </summary>
  1871. public void BeginInit ()
  1872. {
  1873. if (!IsInitialized) {
  1874. oldCanFocus = CanFocus;
  1875. oldTabIndex = tabIndex;
  1876. }
  1877. if (subviews?.Count > 0) {
  1878. foreach (var view in subviews) {
  1879. if (!view.IsInitialized) {
  1880. view.BeginInit ();
  1881. }
  1882. }
  1883. }
  1884. }
  1885. /// <summary>
  1886. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are ending initialized.
  1887. /// </summary>
  1888. public void EndInit ()
  1889. {
  1890. IsInitialized = true;
  1891. if (subviews?.Count > 0) {
  1892. foreach (var view in subviews) {
  1893. if (!view.IsInitialized) {
  1894. view.EndInit ();
  1895. }
  1896. }
  1897. }
  1898. Initialized?.Invoke (this, EventArgs.Empty);
  1899. }
  1900. /// <summary>
  1901. /// Gets or sets the view visibility.
  1902. /// </summary>
  1903. public bool Visible { get; set; } = true;
  1904. bool CanBeVisible (View view)
  1905. {
  1906. if (!view.Visible) {
  1907. return false;
  1908. }
  1909. for (var c = view.SuperView; c != null; c = c.SuperView) {
  1910. if (!c.Visible) {
  1911. return false;
  1912. }
  1913. }
  1914. return true;
  1915. }
  1916. }
  1917. }