View.cs 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375
  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. // Optimizations
  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 initialized. 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 parameter 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 typically 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 the <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. if (x is Pos.PosAbsolute) {
  431. frame = new Rect (x.Anchor (0), frame.Y, frame.Width, frame.Height);
  432. }
  433. textFormatter.Size = frame.Size;
  434. SetNeedsDisplay (frame);
  435. }
  436. }
  437. /// <summary>
  438. /// Gets or sets the Y position for the view (the row). Only used the <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  439. /// </summary>
  440. /// <value>The y position (line).</value>
  441. /// <remarks>
  442. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  443. /// </remarks>
  444. public Pos Y {
  445. get => y;
  446. set {
  447. if (!ValidatePosDim (y, value)) {
  448. throw new ArgumentException ();
  449. }
  450. y = value;
  451. SetNeedsLayout ();
  452. if (y is Pos.PosAbsolute) {
  453. frame = new Rect (frame.X, y.Anchor (0), frame.Width, frame.Height);
  454. }
  455. textFormatter.Size = frame.Size;
  456. SetNeedsDisplay (frame);
  457. }
  458. }
  459. Dim width, height;
  460. /// <summary>
  461. /// Gets or sets the width of the view. Only used the <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  462. /// </summary>
  463. /// <value>The width.</value>
  464. /// <remarks>
  465. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  466. /// </remarks>
  467. public Dim Width {
  468. get => width;
  469. set {
  470. if (!ValidatePosDim (width, value)) {
  471. throw new ArgumentException ();
  472. }
  473. width = value;
  474. SetNeedsLayout ();
  475. if (width is Dim.DimAbsolute) {
  476. frame = new Rect (frame.X, frame.Y, width.Anchor (0), frame.Height);
  477. }
  478. textFormatter.Size = frame.Size;
  479. SetNeedsDisplay (frame);
  480. }
  481. }
  482. /// <summary>
  483. /// Gets or sets the height of the view. Only used the <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  484. /// </summary>
  485. /// <value>The height.</value>
  486. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  487. public Dim Height {
  488. get => height;
  489. set {
  490. if (!ValidatePosDim (height, value)) {
  491. throw new ArgumentException ();
  492. }
  493. height = value;
  494. SetNeedsLayout ();
  495. if (height is Dim.DimAbsolute) {
  496. frame = new Rect (frame.X, frame.Y, frame.Width, height.Anchor (0));
  497. }
  498. textFormatter.Size = frame.Size;
  499. SetNeedsDisplay (frame);
  500. }
  501. }
  502. bool ValidatePosDim (object oldvalue, object newValue)
  503. {
  504. if (!IsInitialized || layoutStyle == LayoutStyle.Absolute || oldvalue == null || oldvalue.GetType () == newValue.GetType () || this is Toplevel) {
  505. return true;
  506. }
  507. if (layoutStyle == LayoutStyle.Computed) {
  508. if (oldvalue.GetType () != newValue.GetType () && !(newValue is Pos.PosAbsolute || newValue is Dim.DimAbsolute)) {
  509. return true;
  510. }
  511. }
  512. return false;
  513. }
  514. /// <summary>
  515. /// Returns the container for this view, or null if this view has not been added to a container.
  516. /// </summary>
  517. /// <value>The super view.</value>
  518. public View SuperView => container;
  519. /// <summary>
  520. /// Initializes a new instance of a <see cref="LayoutStyle.Absolute"/> <see cref="View"/> class with the absolute
  521. /// dimensions specified in the <c>frame</c> parameter.
  522. /// </summary>
  523. /// <param name="frame">The region covered by this view.</param>
  524. /// <remarks>
  525. /// This constructor initialize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Absolute"/>. Use <see cref="View()"/> to
  526. /// initialize a View with <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>
  527. /// </remarks>
  528. public View (Rect frame)
  529. {
  530. Initialize (ustring.Empty, frame, LayoutStyle.Absolute, TextDirection.LeftRight_TopBottom);
  531. }
  532. /// <summary>
  533. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  534. /// </summary>
  535. /// <remarks>
  536. /// <para>
  537. /// 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.
  538. /// The <see cref="Label"/> will be created using <see cref="LayoutStyle.Computed"/>
  539. /// coordinates. The initial size (<see cref="View.Frame"/> will be
  540. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  541. /// </para>
  542. /// <para>
  543. /// If <c>Height</c> is greater than one, word wrapping is provided.
  544. /// </para>
  545. /// <para>
  546. /// This constructor initialize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>.
  547. /// 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.
  548. /// </para>
  549. /// </remarks>
  550. public View () : this (text: string.Empty, direction: TextDirection.LeftRight_TopBottom) { }
  551. /// <summary>
  552. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  553. /// </summary>
  554. /// <remarks>
  555. /// <para>
  556. /// The <see cref="View"/> will be created at the given
  557. /// coordinates with the given string. The size (<see cref="View.Frame"/> will be
  558. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  559. /// </para>
  560. /// <para>
  561. /// No line wrapping is provided.
  562. /// </para>
  563. /// </remarks>
  564. /// <param name="x">column to locate the Label.</param>
  565. /// <param name="y">row to locate the Label.</param>
  566. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  567. public View (int x, int y, ustring text) : this (TextFormatter.CalcRect (x, y, text), text) { }
  568. /// <summary>
  569. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  570. /// </summary>
  571. /// <remarks>
  572. /// <para>
  573. /// The <see cref="View"/> will be created at the given
  574. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  575. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  576. /// </para>
  577. /// <para>
  578. /// If <c>rect.Height</c> is greater than one, word wrapping is provided.
  579. /// </para>
  580. /// </remarks>
  581. /// <param name="rect">Location.</param>
  582. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  583. public View (Rect rect, ustring text)
  584. {
  585. Initialize (text, rect, LayoutStyle.Absolute);
  586. }
  587. /// <summary>
  588. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  589. /// </summary>
  590. /// <remarks>
  591. /// <para>
  592. /// The <see cref="View"/> will be created using <see cref="LayoutStyle.Computed"/>
  593. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  594. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  595. /// </para>
  596. /// <para>
  597. /// If <c>Height</c> is greater than one, word wrapping is provided.
  598. /// </para>
  599. /// </remarks>
  600. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  601. /// <param name="direction">The text direction.</param>
  602. public View (ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  603. {
  604. Initialize (text, Rect.Empty, LayoutStyle.Computed, direction);
  605. }
  606. void Initialize (ustring text, Rect rect, LayoutStyle layoutStyle = LayoutStyle.Computed,
  607. TextDirection direction = TextDirection.LeftRight_TopBottom)
  608. {
  609. textFormatter = new TextFormatter ();
  610. TextDirection = direction;
  611. shortcutHelper = new ShortcutHelper ();
  612. CanFocus = false;
  613. TabIndex = -1;
  614. TabStop = false;
  615. LayoutStyle = layoutStyle;
  616. // BUGBUG: CalcRect doesn't account for line wrapping
  617. Rect r;
  618. if (rect.IsEmpty) {
  619. r = TextFormatter.CalcRect (0, 0, text, direction);
  620. } else {
  621. r = rect;
  622. }
  623. x = Pos.At (r.X);
  624. y = Pos.At (r.Y);
  625. Width = r.Width;
  626. Height = r.Height;
  627. Frame = r;
  628. Text = text;
  629. }
  630. /// <summary>
  631. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  632. /// </summary>
  633. public void SetNeedsDisplay ()
  634. {
  635. SetNeedsDisplay (Bounds);
  636. }
  637. internal bool LayoutNeeded { get; private set; } = true;
  638. internal void SetNeedsLayout ()
  639. {
  640. if (LayoutNeeded)
  641. return;
  642. LayoutNeeded = true;
  643. if (SuperView == null)
  644. return;
  645. SuperView.SetNeedsLayout ();
  646. textFormatter.NeedsFormat = true;
  647. }
  648. /// <summary>
  649. /// Removes the <see cref="SetNeedsLayout"/> setting on this view.
  650. /// </summary>
  651. protected void ClearLayoutNeeded ()
  652. {
  653. LayoutNeeded = false;
  654. }
  655. /// <summary>
  656. /// Flags the view-relative region on this View as needing to be repainted.
  657. /// </summary>
  658. /// <param name="region">The view-relative region that must be flagged for repaint.</param>
  659. public void SetNeedsDisplay (Rect region)
  660. {
  661. if (NeedDisplay.IsEmpty)
  662. NeedDisplay = region;
  663. else {
  664. var x = Math.Min (NeedDisplay.X, region.X);
  665. var y = Math.Min (NeedDisplay.Y, region.Y);
  666. var w = Math.Max (NeedDisplay.Width, region.Width);
  667. var h = Math.Max (NeedDisplay.Height, region.Height);
  668. NeedDisplay = new Rect (x, y, w, h);
  669. }
  670. if (container != null)
  671. container.SetChildNeedsDisplay ();
  672. if (subviews == null)
  673. return;
  674. foreach (var view in subviews)
  675. if (view.Frame.IntersectsWith (region)) {
  676. var childRegion = Rect.Intersect (view.Frame, region);
  677. childRegion.X -= view.Frame.X;
  678. childRegion.Y -= view.Frame.Y;
  679. view.SetNeedsDisplay (childRegion);
  680. }
  681. }
  682. internal bool ChildNeedsDisplay { get; private set; }
  683. /// <summary>
  684. /// Indicates that any child views (in the <see cref="Subviews"/> list) need to be repainted.
  685. /// </summary>
  686. public void SetChildNeedsDisplay ()
  687. {
  688. ChildNeedsDisplay = true;
  689. if (container != null)
  690. container.SetChildNeedsDisplay ();
  691. }
  692. internal bool addingView = false;
  693. /// <summary>
  694. /// Adds a subview (child) to this view.
  695. /// </summary>
  696. /// <remarks>
  697. /// 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"/>
  698. /// </remarks>
  699. public virtual void Add (View view)
  700. {
  701. if (view == null)
  702. return;
  703. if (subviews == null) {
  704. subviews = new List<View> ();
  705. }
  706. if (tabIndexes == null) {
  707. tabIndexes = new List<View> ();
  708. }
  709. subviews.Add (view);
  710. tabIndexes.Add (view);
  711. view.container = this;
  712. if (view.CanFocus) {
  713. addingView = true;
  714. if (SuperView?.CanFocus == false) {
  715. SuperView.addingView = true;
  716. SuperView.CanFocus = true;
  717. SuperView.addingView = false;
  718. }
  719. CanFocus = true;
  720. view.tabIndex = tabIndexes.IndexOf (view);
  721. addingView = false;
  722. }
  723. SetNeedsLayout ();
  724. SetNeedsDisplay ();
  725. OnAdded (view);
  726. if (IsInitialized) {
  727. view.BeginInit ();
  728. view.EndInit ();
  729. }
  730. }
  731. /// <summary>
  732. /// Adds the specified views (children) to the view.
  733. /// </summary>
  734. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  735. /// <remarks>
  736. /// 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"/>
  737. /// </remarks>
  738. public void Add (params View [] views)
  739. {
  740. if (views == null)
  741. return;
  742. foreach (var view in views)
  743. Add (view);
  744. }
  745. /// <summary>
  746. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  747. /// </summary>
  748. public virtual void RemoveAll ()
  749. {
  750. if (subviews == null)
  751. return;
  752. while (subviews.Count > 0) {
  753. Remove (subviews [0]);
  754. }
  755. }
  756. /// <summary>
  757. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  758. /// </summary>
  759. /// <remarks>
  760. /// </remarks>
  761. public virtual void Remove (View view)
  762. {
  763. if (view == null || subviews == null)
  764. return;
  765. SetNeedsLayout ();
  766. SetNeedsDisplay ();
  767. var touched = view.Frame;
  768. subviews.Remove (view);
  769. tabIndexes.Remove (view);
  770. view.container = null;
  771. view.tabIndex = -1;
  772. if (subviews.Count < 1) {
  773. CanFocus = false;
  774. }
  775. foreach (var v in subviews) {
  776. if (v.Frame.IntersectsWith (touched))
  777. view.SetNeedsDisplay ();
  778. }
  779. OnRemoved (view);
  780. if (focused == view) {
  781. focused = null;
  782. }
  783. }
  784. void PerformActionForSubview (View subview, Action<View> action)
  785. {
  786. if (subviews.Contains (subview)) {
  787. action (subview);
  788. }
  789. SetNeedsDisplay ();
  790. subview.SetNeedsDisplay ();
  791. }
  792. /// <summary>
  793. /// Brings the specified subview to the front so it is drawn on top of any other views.
  794. /// </summary>
  795. /// <param name="subview">The subview to send to the front</param>
  796. /// <remarks>
  797. /// <seealso cref="SendSubviewToBack"/>.
  798. /// </remarks>
  799. public void BringSubviewToFront (View subview)
  800. {
  801. PerformActionForSubview (subview, x => {
  802. subviews.Remove (x);
  803. subviews.Add (x);
  804. });
  805. }
  806. /// <summary>
  807. /// Sends the specified subview to the front so it is the first view drawn
  808. /// </summary>
  809. /// <param name="subview">The subview to send to the front</param>
  810. /// <remarks>
  811. /// <seealso cref="BringSubviewToFront(View)"/>.
  812. /// </remarks>
  813. public void SendSubviewToBack (View subview)
  814. {
  815. PerformActionForSubview (subview, x => {
  816. subviews.Remove (x);
  817. subviews.Insert (0, subview);
  818. });
  819. }
  820. /// <summary>
  821. /// Moves the subview backwards in the hierarchy, only one step
  822. /// </summary>
  823. /// <param name="subview">The subview to send backwards</param>
  824. /// <remarks>
  825. /// If you want to send the view all the way to the back use SendSubviewToBack.
  826. /// </remarks>
  827. public void SendSubviewBackwards (View subview)
  828. {
  829. PerformActionForSubview (subview, x => {
  830. var idx = subviews.IndexOf (x);
  831. if (idx > 0) {
  832. subviews.Remove (x);
  833. subviews.Insert (idx - 1, x);
  834. }
  835. });
  836. }
  837. /// <summary>
  838. /// Moves the subview backwards in the hierarchy, only one step
  839. /// </summary>
  840. /// <param name="subview">The subview to send backwards</param>
  841. /// <remarks>
  842. /// If you want to send the view all the way to the back use SendSubviewToBack.
  843. /// </remarks>
  844. public void BringSubviewForward (View subview)
  845. {
  846. PerformActionForSubview (subview, x => {
  847. var idx = subviews.IndexOf (x);
  848. if (idx + 1 < subviews.Count) {
  849. subviews.Remove (x);
  850. subviews.Insert (idx + 1, x);
  851. }
  852. });
  853. }
  854. /// <summary>
  855. /// Clears the view region with the current color.
  856. /// </summary>
  857. /// <remarks>
  858. /// <para>
  859. /// This clears the entire region used by this view.
  860. /// </para>
  861. /// </remarks>
  862. public void Clear ()
  863. {
  864. var h = Frame.Height;
  865. var w = Frame.Width;
  866. for (int line = 0; line < h; line++) {
  867. Move (0, line);
  868. for (int col = 0; col < w; col++)
  869. Driver.AddRune (' ');
  870. }
  871. }
  872. /// <summary>
  873. /// Clears the specified region with the current color.
  874. /// </summary>
  875. /// <remarks>
  876. /// </remarks>
  877. /// <param name="regionScreen">The screen-relative region to clear.</param>
  878. public void Clear (Rect regionScreen)
  879. {
  880. var h = regionScreen.Height;
  881. var w = regionScreen.Width;
  882. for (int line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  883. Driver.Move (regionScreen.X, line);
  884. for (int col = 0; col < w; col++)
  885. Driver.AddRune (' ');
  886. }
  887. }
  888. /// <summary>
  889. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  890. /// </summary>
  891. /// <param name="col">View-relative column.</param>
  892. /// <param name="row">View-relative row.</param>
  893. /// <param name="rcol">Absolute column; screen-relative.</param>
  894. /// <param name="rrow">Absolute row; screen-relative.</param>
  895. /// <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>
  896. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  897. {
  898. // Computes the real row, col relative to the screen.
  899. rrow = row + frame.Y;
  900. rcol = col + frame.X;
  901. var ccontainer = container;
  902. while (ccontainer != null) {
  903. rrow += ccontainer.frame.Y;
  904. rcol += ccontainer.frame.X;
  905. ccontainer = ccontainer.container;
  906. }
  907. // The following ensures that the cursor is always in the screen boundaries.
  908. if (clipped) {
  909. rrow = Math.Min (rrow, Driver.Rows - 1);
  910. rcol = Math.Min (rcol, Driver.Cols - 1);
  911. }
  912. }
  913. /// <summary>
  914. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  915. /// </summary>
  916. /// <returns>The mapped point.</returns>
  917. /// <param name="x">X screen-coordinate point.</param>
  918. /// <param name="y">Y screen-coordinate point.</param>
  919. public Point ScreenToView (int x, int y)
  920. {
  921. if (SuperView == null) {
  922. return new Point (x - Frame.X, y - frame.Y);
  923. } else {
  924. var parent = SuperView.ScreenToView (x, y);
  925. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  926. }
  927. }
  928. /// <summary>
  929. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  930. /// </summary>
  931. internal Rect ViewToScreen (Rect region)
  932. {
  933. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  934. return new Rect (x, y, region.Width, region.Height);
  935. }
  936. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  937. internal Rect ScreenClip (Rect regionScreen)
  938. {
  939. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  940. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  941. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  942. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  943. return new Rect (x, y, w, h);
  944. }
  945. /// <summary>
  946. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  947. /// </summary>
  948. /// <returns>The existing driver's clip region, which can be then re-applied by setting <c><see cref="Driver"/>.Clip</c> (<see cref="ConsoleDriver.Clip"/>).</returns>
  949. /// <remarks>
  950. /// <see cref="Bounds"/> is View-relative.
  951. /// </remarks>
  952. public Rect ClipToBounds ()
  953. {
  954. return SetClip (Bounds);
  955. }
  956. /// <summary>
  957. /// Sets the clip region to the specified view-relative region.
  958. /// </summary>
  959. /// <returns>The previous screen-relative clip region.</returns>
  960. /// <param name="region">View-relative clip region.</param>
  961. public Rect SetClip (Rect region)
  962. {
  963. var previous = Driver.Clip;
  964. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  965. return previous;
  966. }
  967. /// <summary>
  968. /// Draws a frame in the current view, clipped by the boundary of this view
  969. /// </summary>
  970. /// <param name="region">View-relative region for the frame to be drawn.</param>
  971. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  972. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  973. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  974. {
  975. var scrRect = ViewToScreen (region);
  976. var savedClip = ClipToBounds ();
  977. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  978. Driver.Clip = savedClip;
  979. }
  980. /// <summary>
  981. /// Utility function to draw strings that contain a hotkey.
  982. /// </summary>
  983. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  984. /// <param name="hotColor">Hot color.</param>
  985. /// <param name="normalColor">Normal color.</param>
  986. /// <remarks>
  987. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  988. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  989. /// </remarks>
  990. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  991. {
  992. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  993. Application.Driver.SetAttribute (normalColor);
  994. foreach (var rune in text) {
  995. if (rune == hotkeySpec) {
  996. Application.Driver.SetAttribute (hotColor);
  997. continue;
  998. }
  999. Application.Driver.AddRune (rune);
  1000. Application.Driver.SetAttribute (normalColor);
  1001. }
  1002. }
  1003. /// <summary>
  1004. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  1005. /// </summary>
  1006. /// <param name="text">String to display, the underscore before a letter flags the next letter as the hotkey.</param>
  1007. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  1008. /// <param name="scheme">The color scheme to use.</param>
  1009. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  1010. {
  1011. if (focused)
  1012. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  1013. else
  1014. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  1015. }
  1016. /// <summary>
  1017. /// This moves the cursor to the specified column and row in the view.
  1018. /// </summary>
  1019. /// <returns>The move.</returns>
  1020. /// <param name="col">Col.</param>
  1021. /// <param name="row">Row.</param>
  1022. public void Move (int col, int row)
  1023. {
  1024. if (Driver.Rows == 0) {
  1025. return;
  1026. }
  1027. ViewToScreen (col, row, out var rcol, out var rrow);
  1028. Driver.Move (rcol, rrow);
  1029. }
  1030. /// <summary>
  1031. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1032. /// </summary>
  1033. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1034. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1035. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1036. /// the last focused view. Views should make sure that they place the cursor
  1037. /// in a visually sensible place.
  1038. public virtual void PositionCursor ()
  1039. {
  1040. if (!CanBeVisible (this)) {
  1041. return;
  1042. }
  1043. if (focused?.Frame.Width > 0 && focused.Frame.Height > 0) {
  1044. focused.PositionCursor ();
  1045. } else {
  1046. if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
  1047. Move (textFormatter.HotKeyPos == -1 ? 0 : textFormatter.CursorPosition, 0);
  1048. } else {
  1049. Move (frame.X, frame.Y);
  1050. }
  1051. }
  1052. }
  1053. bool hasFocus;
  1054. /// <inheritdoc/>
  1055. public override bool HasFocus {
  1056. get {
  1057. return hasFocus;
  1058. }
  1059. }
  1060. void SetHasFocus (bool value, View view)
  1061. {
  1062. if (hasFocus != value) {
  1063. hasFocus = value;
  1064. if (value) {
  1065. OnEnter (view);
  1066. } else {
  1067. OnLeave (view);
  1068. }
  1069. SetNeedsDisplay ();
  1070. }
  1071. // Remove focus down the chain of subviews if focus is removed
  1072. if (!value && focused != null) {
  1073. focused.OnLeave (view);
  1074. focused.SetHasFocus (false, view);
  1075. focused = null;
  1076. }
  1077. }
  1078. /// <summary>
  1079. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  1080. /// </summary>
  1081. public class FocusEventArgs : EventArgs {
  1082. /// <summary>
  1083. /// Constructs.
  1084. /// </summary>
  1085. /// <param name="view">The view that gets or loses focus.</param>
  1086. public FocusEventArgs (View view) { View = view; }
  1087. /// <summary>
  1088. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  1089. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1090. /// </summary>
  1091. public bool Handled { get; set; }
  1092. /// <summary>
  1093. /// Indicates the current view that gets or loses focus.
  1094. /// </summary>
  1095. public View View { get; set; }
  1096. }
  1097. /// <summary>
  1098. /// Method invoked when a subview is being added to this view.
  1099. /// </summary>
  1100. /// <param name="view">The subview being added.</param>
  1101. public virtual void OnAdded (View view)
  1102. {
  1103. view.Added?.Invoke (this);
  1104. }
  1105. /// <summary>
  1106. /// Method invoked when a subview is being removed from this view.
  1107. /// </summary>
  1108. /// <param name="view">The subview being removed.</param>
  1109. public virtual void OnRemoved (View view)
  1110. {
  1111. view.Removed?.Invoke (this);
  1112. }
  1113. /// <inheritdoc/>
  1114. public override bool OnEnter (View view)
  1115. {
  1116. FocusEventArgs args = new FocusEventArgs (view);
  1117. Enter?.Invoke (args);
  1118. if (args.Handled)
  1119. return true;
  1120. if (base.OnEnter (view))
  1121. return true;
  1122. return false;
  1123. }
  1124. /// <inheritdoc/>
  1125. public override bool OnLeave (View view)
  1126. {
  1127. FocusEventArgs args = new FocusEventArgs (view);
  1128. Leave?.Invoke (args);
  1129. if (args.Handled)
  1130. return true;
  1131. if (base.OnLeave (view))
  1132. return true;
  1133. return false;
  1134. }
  1135. /// <summary>
  1136. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1137. /// </summary>
  1138. /// <value>The focused.</value>
  1139. public View Focused => focused;
  1140. /// <summary>
  1141. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1142. /// </summary>
  1143. /// <value>The most focused.</value>
  1144. public View MostFocused {
  1145. get {
  1146. if (Focused == null)
  1147. return null;
  1148. var most = Focused.MostFocused;
  1149. if (most != null)
  1150. return most;
  1151. return Focused;
  1152. }
  1153. }
  1154. /// <summary>
  1155. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1156. /// color scheme.
  1157. /// </summary>
  1158. public ColorScheme ColorScheme {
  1159. get {
  1160. if (colorScheme == null)
  1161. return SuperView?.ColorScheme;
  1162. return colorScheme;
  1163. }
  1164. set {
  1165. if (colorScheme != value) {
  1166. colorScheme = value;
  1167. SetNeedsDisplay ();
  1168. }
  1169. }
  1170. }
  1171. ColorScheme colorScheme;
  1172. /// <summary>
  1173. /// Displays the specified character in the specified column and row of the View.
  1174. /// </summary>
  1175. /// <param name="col">Column (view-relative).</param>
  1176. /// <param name="row">Row (view-relative).</param>
  1177. /// <param name="ch">Ch.</param>
  1178. public void AddRune (int col, int row, Rune ch)
  1179. {
  1180. if (row < 0 || col < 0)
  1181. return;
  1182. if (row > frame.Height - 1 || col > frame.Width - 1)
  1183. return;
  1184. Move (col, row);
  1185. Driver.AddRune (ch);
  1186. }
  1187. /// <summary>
  1188. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  1189. /// </summary>
  1190. protected void ClearNeedsDisplay ()
  1191. {
  1192. NeedDisplay = Rect.Empty;
  1193. ChildNeedsDisplay = false;
  1194. }
  1195. /// <summary>
  1196. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1197. /// </summary>
  1198. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1199. /// <remarks>
  1200. /// <para>
  1201. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1202. /// </para>
  1203. /// <para>
  1204. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1205. /// the last color that was set globally on the driver.
  1206. /// </para>
  1207. /// <para>
  1208. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1209. /// larger than the <c>region</c> parameter.
  1210. /// </para>
  1211. /// </remarks>
  1212. public virtual void Redraw (Rect bounds)
  1213. {
  1214. if (!CanBeVisible (this)) {
  1215. return;
  1216. }
  1217. var clipRect = new Rect (Point.Empty, frame.Size);
  1218. if (ColorScheme != null) {
  1219. Driver.SetAttribute (HasFocus ? ColorScheme.Focus : ColorScheme.Normal);
  1220. }
  1221. if (!ustring.IsNullOrEmpty (Text)) {
  1222. Clear ();
  1223. // Draw any Text
  1224. if (textFormatter != null) {
  1225. textFormatter.NeedsFormat = true;
  1226. }
  1227. textFormatter?.Draw (ViewToScreen (Bounds), HasFocus ? ColorScheme.Focus : ColorScheme.Normal, HasFocus ? ColorScheme.HotFocus : ColorScheme.HotNormal);
  1228. }
  1229. // Invoke DrawContentEvent
  1230. OnDrawContent (bounds);
  1231. if (subviews != null) {
  1232. foreach (var view in subviews) {
  1233. if (!view.NeedDisplay.IsEmpty || view.ChildNeedsDisplay || view.LayoutNeeded) {
  1234. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1235. if (view.LayoutNeeded)
  1236. view.LayoutSubviews ();
  1237. // Draw the subview
  1238. // Use the view's bounds (view-relative; Location will always be (0,0)
  1239. if (view.Visible && view.Frame.Width > 0 && view.Frame.Height > 0) {
  1240. view.OnDrawContent (view.Bounds);
  1241. view.Redraw (view.Bounds);
  1242. }
  1243. }
  1244. view.NeedDisplay = Rect.Empty;
  1245. view.ChildNeedsDisplay = false;
  1246. }
  1247. }
  1248. }
  1249. ClearLayoutNeeded ();
  1250. ClearNeedsDisplay ();
  1251. }
  1252. /// <summary>
  1253. /// Event invoked when the content area of the View is to be drawn.
  1254. /// </summary>
  1255. /// <remarks>
  1256. /// <para>
  1257. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1258. /// </para>
  1259. /// <para>
  1260. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1261. /// </para>
  1262. /// </remarks>
  1263. public event Action<Rect> DrawContent;
  1264. /// <summary>
  1265. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1266. /// </summary>
  1267. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1268. /// <remarks>
  1269. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1270. /// </remarks>
  1271. public virtual void OnDrawContent (Rect viewport)
  1272. {
  1273. DrawContent?.Invoke (viewport);
  1274. }
  1275. /// <summary>
  1276. /// Causes the specified subview to have focus.
  1277. /// </summary>
  1278. /// <param name="view">View.</param>
  1279. void SetFocus (View view)
  1280. {
  1281. if (view == null)
  1282. return;
  1283. //Console.WriteLine ($"Request to focus {view}");
  1284. if (!view.CanFocus || !view.Visible)
  1285. return;
  1286. if (focused?.hasFocus == true && focused == view)
  1287. return;
  1288. // Make sure that this view is a subview
  1289. View c;
  1290. for (c = view.container; c != null; c = c.container)
  1291. if (c == this)
  1292. break;
  1293. if (c == null)
  1294. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1295. if (focused != null)
  1296. focused.SetHasFocus (false, view);
  1297. var f = focused;
  1298. focused = view;
  1299. focused.SetHasFocus (true, f);
  1300. focused.EnsureFocus ();
  1301. // Send focus upwards
  1302. SuperView?.SetFocus (this);
  1303. }
  1304. /// <summary>
  1305. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  1306. /// </summary>
  1307. public void SetFocus ()
  1308. {
  1309. if (!CanBeVisible (this)) {
  1310. return;
  1311. }
  1312. SuperView?.SetFocus (this);
  1313. }
  1314. /// <summary>
  1315. /// Defines the event arguments for <see cref="KeyEvent"/>
  1316. /// </summary>
  1317. public class KeyEventEventArgs : EventArgs {
  1318. /// <summary>
  1319. /// Constructs.
  1320. /// </summary>
  1321. /// <param name="ke"></param>
  1322. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  1323. /// <summary>
  1324. /// The <see cref="KeyEvent"/> for the event.
  1325. /// </summary>
  1326. public KeyEvent KeyEvent { get; set; }
  1327. /// <summary>
  1328. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1329. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1330. /// </summary>
  1331. public bool Handled { get; set; } = false;
  1332. }
  1333. /// <summary>
  1334. /// Invoked when a character key is pressed and occurs after the key up event.
  1335. /// </summary>
  1336. public event Action<KeyEventEventArgs> KeyPress;
  1337. /// <inheritdoc/>
  1338. public override bool ProcessKey (KeyEvent keyEvent)
  1339. {
  1340. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1341. KeyPress?.Invoke (args);
  1342. if (args.Handled)
  1343. return true;
  1344. Focused?.KeyPress?.Invoke (args);
  1345. if (args.Handled)
  1346. return true;
  1347. if (Focused?.ProcessKey (keyEvent) == true)
  1348. return true;
  1349. return false;
  1350. }
  1351. /// <inheritdoc/>
  1352. public override bool ProcessHotKey (KeyEvent keyEvent)
  1353. {
  1354. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1355. KeyPress?.Invoke (args);
  1356. if (args.Handled)
  1357. return true;
  1358. Focused?.KeyPress?.Invoke (args);
  1359. if (args.Handled)
  1360. return true;
  1361. if (Focused?.ProcessKey (keyEvent) == true)
  1362. return true;
  1363. if (subviews == null || subviews.Count == 0)
  1364. return false;
  1365. foreach (var view in subviews)
  1366. if (view.ProcessHotKey (keyEvent))
  1367. return true;
  1368. return false;
  1369. }
  1370. /// <inheritdoc/>
  1371. public override bool ProcessColdKey (KeyEvent keyEvent)
  1372. {
  1373. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1374. KeyPress?.Invoke (args);
  1375. if (args.Handled)
  1376. return true;
  1377. Focused?.KeyPress?.Invoke (args);
  1378. if (args.Handled)
  1379. return true;
  1380. if (Focused?.ProcessKey (keyEvent) == true)
  1381. return true;
  1382. if (subviews == null || subviews.Count == 0)
  1383. return false;
  1384. foreach (var view in subviews)
  1385. if (view.ProcessColdKey (keyEvent))
  1386. return true;
  1387. return false;
  1388. }
  1389. /// <summary>
  1390. /// Invoked when a key is pressed
  1391. /// </summary>
  1392. public event Action<KeyEventEventArgs> KeyDown;
  1393. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1394. public override bool OnKeyDown (KeyEvent keyEvent)
  1395. {
  1396. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1397. KeyDown?.Invoke (args);
  1398. if (args.Handled) {
  1399. return true;
  1400. }
  1401. if (Focused?.OnKeyDown (keyEvent) == true) {
  1402. return true;
  1403. }
  1404. return false;
  1405. }
  1406. /// <summary>
  1407. /// Invoked when a key is released
  1408. /// </summary>
  1409. public event Action<KeyEventEventArgs> KeyUp;
  1410. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1411. public override bool OnKeyUp (KeyEvent keyEvent)
  1412. {
  1413. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1414. KeyUp?.Invoke (args);
  1415. if (args.Handled) {
  1416. return true;
  1417. }
  1418. if (Focused?.OnKeyUp (keyEvent) == true) {
  1419. return true;
  1420. }
  1421. return false;
  1422. }
  1423. /// <summary>
  1424. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1425. /// </summary>
  1426. public void EnsureFocus ()
  1427. {
  1428. if (focused == null && subviews?.Count > 0) {
  1429. if (FocusDirection == Direction.Forward) {
  1430. FocusFirst ();
  1431. } else {
  1432. FocusLast ();
  1433. }
  1434. }
  1435. }
  1436. /// <summary>
  1437. /// Focuses the first focusable subview if one exists.
  1438. /// </summary>
  1439. public void FocusFirst ()
  1440. {
  1441. if (!CanBeVisible (this)) {
  1442. return;
  1443. }
  1444. if (tabIndexes == null) {
  1445. SuperView?.SetFocus (this);
  1446. return;
  1447. }
  1448. foreach (var view in tabIndexes) {
  1449. if (view.CanFocus && view.tabStop && view.Visible) {
  1450. SetFocus (view);
  1451. return;
  1452. }
  1453. }
  1454. }
  1455. /// <summary>
  1456. /// Focuses the last focusable subview if one exists.
  1457. /// </summary>
  1458. public void FocusLast ()
  1459. {
  1460. if (!CanBeVisible (this)) {
  1461. return;
  1462. }
  1463. if (tabIndexes == null) {
  1464. SuperView?.SetFocus (this);
  1465. return;
  1466. }
  1467. for (int i = tabIndexes.Count; i > 0;) {
  1468. i--;
  1469. View v = tabIndexes [i];
  1470. if (v.CanFocus && v.tabStop && v.Visible) {
  1471. SetFocus (v);
  1472. return;
  1473. }
  1474. }
  1475. }
  1476. /// <summary>
  1477. /// Focuses the previous view.
  1478. /// </summary>
  1479. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1480. public bool FocusPrev ()
  1481. {
  1482. if (!CanBeVisible (this)) {
  1483. return false;
  1484. }
  1485. FocusDirection = Direction.Backward;
  1486. if (tabIndexes == null || tabIndexes.Count == 0)
  1487. return false;
  1488. if (focused == null) {
  1489. FocusLast ();
  1490. return focused != null;
  1491. }
  1492. int focused_idx = -1;
  1493. for (int i = tabIndexes.Count; i > 0;) {
  1494. i--;
  1495. View w = tabIndexes [i];
  1496. if (w.HasFocus) {
  1497. if (w.FocusPrev ())
  1498. return true;
  1499. focused_idx = i;
  1500. continue;
  1501. }
  1502. if (w.CanFocus && focused_idx != -1 && w.tabStop && w.Visible) {
  1503. focused.SetHasFocus (false, w);
  1504. if (w != null && w.CanFocus && w.tabStop && w.Visible)
  1505. w.FocusLast ();
  1506. SetFocus (w);
  1507. return true;
  1508. }
  1509. }
  1510. if (focused != null) {
  1511. focused.SetHasFocus (false, this);
  1512. focused = null;
  1513. }
  1514. return false;
  1515. }
  1516. /// <summary>
  1517. /// Focuses the next view.
  1518. /// </summary>
  1519. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1520. public bool FocusNext ()
  1521. {
  1522. if (!CanBeVisible (this)) {
  1523. return false;
  1524. }
  1525. FocusDirection = Direction.Forward;
  1526. if (tabIndexes == null || tabIndexes.Count == 0)
  1527. return false;
  1528. if (focused == null) {
  1529. FocusFirst ();
  1530. return focused != null;
  1531. }
  1532. int n = tabIndexes.Count;
  1533. int focused_idx = -1;
  1534. for (int i = 0; i < n; i++) {
  1535. View w = tabIndexes [i];
  1536. if (w.HasFocus) {
  1537. if (w.FocusNext ())
  1538. return true;
  1539. focused_idx = i;
  1540. continue;
  1541. }
  1542. if (w.CanFocus && focused_idx != -1 && w.tabStop && w.Visible) {
  1543. focused.SetHasFocus (false, w);
  1544. if (w != null && w.CanFocus && w.tabStop && w.Visible)
  1545. w.FocusFirst ();
  1546. SetFocus (w);
  1547. return true;
  1548. }
  1549. }
  1550. if (focused != null) {
  1551. focused.SetHasFocus (false, this);
  1552. focused = null;
  1553. }
  1554. return false;
  1555. }
  1556. /// <summary>
  1557. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1558. /// </summary>
  1559. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1560. /// <remarks>
  1561. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1562. /// </remarks>
  1563. internal void SetRelativeLayout (Rect hostFrame)
  1564. {
  1565. int w, h, _x, _y;
  1566. if (x is Pos.PosCenter) {
  1567. if (width == null)
  1568. w = hostFrame.Width;
  1569. else
  1570. w = width.Anchor (hostFrame.Width);
  1571. _x = x.Anchor (hostFrame.Width - w);
  1572. } else {
  1573. if (x == null)
  1574. _x = 0;
  1575. else
  1576. _x = x.Anchor (hostFrame.Width);
  1577. if (width == null)
  1578. w = hostFrame.Width;
  1579. else if (width is Dim.DimFactor && !((Dim.DimFactor)width).IsFromRemaining ())
  1580. w = width.Anchor (hostFrame.Width);
  1581. else
  1582. w = Math.Max (width.Anchor (hostFrame.Width - _x), 0);
  1583. }
  1584. if (y is Pos.PosCenter) {
  1585. if (height == null)
  1586. h = hostFrame.Height;
  1587. else
  1588. h = height.Anchor (hostFrame.Height);
  1589. _y = y.Anchor (hostFrame.Height - h);
  1590. } else {
  1591. if (y == null)
  1592. _y = 0;
  1593. else
  1594. _y = y.Anchor (hostFrame.Height);
  1595. if (height == null)
  1596. h = hostFrame.Height;
  1597. else if (height is Dim.DimFactor && !((Dim.DimFactor)height).IsFromRemaining ())
  1598. h = height.Anchor (hostFrame.Height);
  1599. else
  1600. h = Math.Max (height.Anchor (hostFrame.Height - _y), 0);
  1601. }
  1602. var r = new Rect (_x, _y, w, h);
  1603. if (Frame != r) {
  1604. Frame = new Rect (_x, _y, w, h);
  1605. }
  1606. }
  1607. // https://en.wikipedia.org/wiki/Topological_sorting
  1608. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1609. {
  1610. var result = new List<View> ();
  1611. // Set of all nodes with no incoming edges
  1612. var S = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  1613. while (S.Any ()) {
  1614. // remove a node n from S
  1615. var n = S.First ();
  1616. S.Remove (n);
  1617. // add n to tail of L
  1618. if (n != this?.SuperView)
  1619. result.Add (n);
  1620. // for each node m with an edge e from n to m do
  1621. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1622. var m = e.To;
  1623. // remove edge e from the graph
  1624. edges.Remove (e);
  1625. // if m has no other incoming edges then
  1626. if (edges.All (me => !me.To.Equals (m)) && m != this?.SuperView) {
  1627. // insert m into S
  1628. S.Add (m);
  1629. }
  1630. }
  1631. }
  1632. if (edges.Any () && edges.First ().From != Application.Top) {
  1633. if (!ReferenceEquals (edges.First ().From, edges.First ().To)) {
  1634. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {edges.First ().From}. Did you forget to add it to {this}?");
  1635. } else {
  1636. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1637. }
  1638. } else {
  1639. // return L (a topologically sorted order)
  1640. return result;
  1641. }
  1642. }
  1643. /// <summary>
  1644. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1645. /// </summary>
  1646. public class LayoutEventArgs : EventArgs {
  1647. /// <summary>
  1648. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  1649. /// </summary>
  1650. public Rect OldBounds { get; set; }
  1651. }
  1652. /// <summary>
  1653. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1654. /// </summary>
  1655. /// <remarks>
  1656. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1657. /// </remarks>
  1658. public event Action<LayoutEventArgs> LayoutStarted;
  1659. /// <summary>
  1660. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  1661. /// </summary>
  1662. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  1663. {
  1664. LayoutStarted?.Invoke (args);
  1665. }
  1666. /// <summary>
  1667. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  1668. /// </summary>
  1669. /// <remarks>
  1670. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  1671. /// </remarks>
  1672. public event Action<LayoutEventArgs> LayoutComplete;
  1673. /// <summary>
  1674. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  1675. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  1676. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  1677. /// </summary>
  1678. public event EventHandler Initialized;
  1679. /// <summary>
  1680. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  1681. /// </summary>
  1682. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  1683. {
  1684. LayoutComplete?.Invoke (args);
  1685. }
  1686. /// <summary>
  1687. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  1688. /// response to the container view or terminal resizing.
  1689. /// </summary>
  1690. /// <remarks>
  1691. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  1692. /// </remarks>
  1693. public virtual void LayoutSubviews ()
  1694. {
  1695. if (!LayoutNeeded) {
  1696. return;
  1697. }
  1698. Rect oldBounds = Bounds;
  1699. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  1700. textFormatter.Size = Bounds.Size;
  1701. // Sort out the dependencies of the X, Y, Width, Height properties
  1702. var nodes = new HashSet<View> ();
  1703. var edges = new HashSet<(View, View)> ();
  1704. void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1705. {
  1706. if (pos is Pos.PosView pv) {
  1707. if (pv.Target != this) {
  1708. nEdges.Add ((pv.Target, from));
  1709. }
  1710. foreach (var v in from.InternalSubviews) {
  1711. CollectAll (v, ref nNodes, ref nEdges);
  1712. }
  1713. return;
  1714. }
  1715. if (pos is Pos.PosCombine pc) {
  1716. foreach (var v in from.InternalSubviews) {
  1717. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  1718. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  1719. }
  1720. }
  1721. }
  1722. void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1723. {
  1724. if (dim is Dim.DimView dv) {
  1725. if (dv.Target != this) {
  1726. nEdges.Add ((dv.Target, from));
  1727. }
  1728. foreach (var v in from.InternalSubviews) {
  1729. CollectAll (v, ref nNodes, ref nEdges);
  1730. }
  1731. return;
  1732. }
  1733. if (dim is Dim.DimCombine dc) {
  1734. foreach (var v in from.InternalSubviews) {
  1735. CollectDim (dc.left, from, ref nNodes, ref nEdges);
  1736. CollectDim (dc.right, from, ref nNodes, ref nEdges);
  1737. }
  1738. }
  1739. }
  1740. void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  1741. {
  1742. foreach (var v in from.InternalSubviews) {
  1743. nNodes.Add (v);
  1744. if (v.layoutStyle != LayoutStyle.Computed) {
  1745. continue;
  1746. }
  1747. CollectPos (v.X, v, ref nNodes, ref nEdges);
  1748. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  1749. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  1750. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  1751. }
  1752. }
  1753. CollectAll (this, ref nodes, ref edges);
  1754. var ordered = TopologicalSort (nodes, edges);
  1755. foreach (var v in ordered) {
  1756. if (v.LayoutStyle == LayoutStyle.Computed) {
  1757. v.SetRelativeLayout (Frame);
  1758. }
  1759. v.LayoutSubviews ();
  1760. v.LayoutNeeded = false;
  1761. }
  1762. if (SuperView == Application.Top && LayoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1763. SetRelativeLayout (Frame);
  1764. }
  1765. LayoutNeeded = false;
  1766. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  1767. }
  1768. /// <summary>
  1769. /// The text displayed by the <see cref="View"/>.
  1770. /// </summary>
  1771. /// <remarks>
  1772. /// <para>
  1773. /// If provided, the text will be drawn before any subviews are drawn.
  1774. /// </para>
  1775. /// <para>
  1776. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  1777. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  1778. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  1779. /// is 1, the text will be clipped.
  1780. /// </para>
  1781. /// <para>
  1782. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  1783. /// <c>(Rune)0xffff</c>.
  1784. /// </para>
  1785. /// </remarks>
  1786. public virtual ustring Text {
  1787. get => textFormatter.Text;
  1788. set {
  1789. textFormatter.Text = value;
  1790. var canResize = ResizeView (autoSize);
  1791. if (canResize && textFormatter.Size != Bounds.Size) {
  1792. Bounds = new Rect (new Point (Bounds.X, Bounds.Y), textFormatter.Size);
  1793. } else if (!canResize && textFormatter.Size != Bounds.Size) {
  1794. textFormatter.Size = Bounds.Size;
  1795. }
  1796. SetNeedsLayout ();
  1797. SetNeedsDisplay ();
  1798. }
  1799. }
  1800. /// <summary>
  1801. /// Used by <see cref="Text"/> to resize the view's <see cref="Bounds"/> with the <see cref="TextFormatter.Size"/>.
  1802. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="Width"/> and <see cref="Height"/> are null or
  1803. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  1804. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  1805. /// </summary>
  1806. public virtual bool AutoSize {
  1807. get => autoSize;
  1808. set {
  1809. var v = ResizeView (value);
  1810. textFormatter.AutoSize = v;
  1811. if (autoSize != v) {
  1812. autoSize = v;
  1813. textFormatter.NeedsFormat = true;
  1814. SetNeedsLayout ();
  1815. SetNeedsDisplay ();
  1816. }
  1817. }
  1818. }
  1819. /// <summary>
  1820. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  1821. /// </summary>
  1822. /// <value>The text alignment.</value>
  1823. public virtual TextAlignment TextAlignment {
  1824. get => textFormatter.Alignment;
  1825. set {
  1826. textFormatter.Alignment = value;
  1827. SetNeedsDisplay ();
  1828. }
  1829. }
  1830. /// <summary>
  1831. /// Gets or sets how the View's <see cref="Text"/> is aligned verticaly when drawn. Changing this property will redisplay the <see cref="View"/>.
  1832. /// </summary>
  1833. /// <value>The text alignment.</value>
  1834. public virtual VerticalTextAlignment VerticalTextAlignment {
  1835. get => textFormatter.VerticalAlignment;
  1836. set {
  1837. textFormatter.VerticalAlignment = value;
  1838. SetNeedsDisplay ();
  1839. }
  1840. }
  1841. /// <summary>
  1842. /// Gets or sets the direction of the View's <see cref="Text"/>. Changing this property will redisplay the <see cref="View"/>.
  1843. /// </summary>
  1844. /// <value>The text alignment.</value>
  1845. public virtual TextDirection TextDirection {
  1846. get => textFormatter.Direction;
  1847. set {
  1848. if (textFormatter.Direction != value) {
  1849. textFormatter.Direction = value;
  1850. if (IsInitialized && AutoSize) {
  1851. ResizeView (true);
  1852. } else if (IsInitialized) {
  1853. var b = new Rect (Bounds.X, Bounds.Y, Bounds.Height, Bounds.Width);
  1854. SetWidthHeight (b);
  1855. }
  1856. textFormatter.Size = Bounds.Size;
  1857. SetNeedsDisplay ();
  1858. }
  1859. }
  1860. }
  1861. /// <summary>
  1862. /// Get or sets if the <see cref="View"/> was already initialized.
  1863. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  1864. /// </summary>
  1865. public bool IsInitialized { get; set; }
  1866. /// <summary>
  1867. /// Pretty prints the View
  1868. /// </summary>
  1869. /// <returns></returns>
  1870. public override string ToString ()
  1871. {
  1872. return $"{GetType ().Name}({Id})({Frame})";
  1873. }
  1874. bool ResizeView (bool autoSize)
  1875. {
  1876. if (!autoSize) {
  1877. return false;
  1878. }
  1879. var aSize = autoSize;
  1880. Rect nBounds = TextFormatter.CalcRect (Bounds.X, Bounds.Y, Text, textFormatter.Direction);
  1881. if (textFormatter.Size != nBounds.Size) {
  1882. textFormatter.Size = nBounds.Size;
  1883. }
  1884. if ((textFormatter.Size != Bounds.Size || textFormatter.Size != nBounds.Size)
  1885. && (((width == null || width is Dim.DimAbsolute) && (Bounds.Width == 0
  1886. || autoSize && Bounds.Width != nBounds.Width))
  1887. || ((height == null || height is Dim.DimAbsolute) && (Bounds.Height == 0
  1888. || autoSize && Bounds.Height != nBounds.Height)))) {
  1889. aSize = SetWidthHeight (nBounds);
  1890. }
  1891. return aSize;
  1892. }
  1893. bool SetWidthHeight (Rect nBounds)
  1894. {
  1895. bool aSize = false;
  1896. var canSizeW = SetWidth (nBounds.Width, out int rW);
  1897. var canSizeH = SetHeight (nBounds.Height, out int rH);
  1898. if (canSizeW) {
  1899. aSize = true;
  1900. width = rW;
  1901. }
  1902. if (canSizeH) {
  1903. aSize = true;
  1904. height = rH;
  1905. }
  1906. if (aSize) {
  1907. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  1908. textFormatter.Size = Bounds.Size;
  1909. }
  1910. return aSize;
  1911. }
  1912. /// <summary>
  1913. /// Specifies the event arguments for <see cref="MouseEvent"/>
  1914. /// </summary>
  1915. public class MouseEventArgs : EventArgs {
  1916. /// <summary>
  1917. /// Constructs.
  1918. /// </summary>
  1919. /// <param name="me"></param>
  1920. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  1921. /// <summary>
  1922. /// The <see cref="MouseEvent"/> for the event.
  1923. /// </summary>
  1924. public MouseEvent MouseEvent { get; set; }
  1925. /// <summary>
  1926. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  1927. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1928. /// </summary>
  1929. public bool Handled { get; set; }
  1930. }
  1931. /// <inheritdoc/>
  1932. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1933. {
  1934. if (!CanBeVisible (this)) {
  1935. return false;
  1936. }
  1937. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1938. MouseEnter?.Invoke (args);
  1939. if (args.Handled)
  1940. return true;
  1941. if (base.OnMouseEnter (mouseEvent))
  1942. return true;
  1943. return false;
  1944. }
  1945. /// <inheritdoc/>
  1946. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1947. {
  1948. if (!CanBeVisible (this)) {
  1949. return false;
  1950. }
  1951. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1952. MouseLeave?.Invoke (args);
  1953. if (args.Handled)
  1954. return true;
  1955. if (base.OnMouseLeave (mouseEvent))
  1956. return true;
  1957. return false;
  1958. }
  1959. /// <summary>
  1960. /// Method invoked when a mouse event is generated
  1961. /// </summary>
  1962. /// <param name="mouseEvent"></param>
  1963. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  1964. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  1965. {
  1966. if (!CanBeVisible (this)) {
  1967. return false;
  1968. }
  1969. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  1970. OnMouseClick (args);
  1971. if (args.Handled)
  1972. return true;
  1973. if (MouseEvent (mouseEvent))
  1974. return true;
  1975. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  1976. if (CanFocus && !HasFocus && SuperView != null) {
  1977. SuperView.SetFocus (this);
  1978. SetNeedsDisplay ();
  1979. }
  1980. return true;
  1981. }
  1982. return false;
  1983. }
  1984. /// <summary>
  1985. /// Invokes the MouseClick event.
  1986. /// </summary>
  1987. protected void OnMouseClick (MouseEventArgs args) => MouseClick?.Invoke (args);
  1988. /// <inheritdoc/>
  1989. protected override void Dispose (bool disposing)
  1990. {
  1991. for (int i = InternalSubviews.Count - 1; i >= 0; i--) {
  1992. View subview = InternalSubviews [i];
  1993. Remove (subview);
  1994. subview.Dispose ();
  1995. }
  1996. base.Dispose (disposing);
  1997. }
  1998. /// <summary>
  1999. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are beginning initialized.
  2000. /// </summary>
  2001. public void BeginInit ()
  2002. {
  2003. if (!IsInitialized) {
  2004. oldCanFocus = CanFocus;
  2005. oldTabIndex = tabIndex;
  2006. }
  2007. if (subviews?.Count > 0) {
  2008. foreach (var view in subviews) {
  2009. if (!view.IsInitialized) {
  2010. view.BeginInit ();
  2011. }
  2012. }
  2013. }
  2014. }
  2015. /// <summary>
  2016. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are ending initialized.
  2017. /// </summary>
  2018. public void EndInit ()
  2019. {
  2020. IsInitialized = true;
  2021. if (subviews?.Count > 0) {
  2022. foreach (var view in subviews) {
  2023. if (!view.IsInitialized) {
  2024. view.EndInit ();
  2025. }
  2026. }
  2027. }
  2028. Initialized?.Invoke (this, EventArgs.Empty);
  2029. }
  2030. /// <summary>
  2031. /// Gets or sets the view visibility.
  2032. /// </summary>
  2033. public bool Visible { get; set; } = true;
  2034. bool CanBeVisible (View view)
  2035. {
  2036. if (!view.Visible) {
  2037. return false;
  2038. }
  2039. for (var c = view.SuperView; c != null; c = c.SuperView) {
  2040. if (!c.Visible) {
  2041. return false;
  2042. }
  2043. }
  2044. return true;
  2045. }
  2046. bool CanSetWidth (int desiredWidth, out int resultWidth)
  2047. {
  2048. int w = desiredWidth;
  2049. bool canSetWidth;
  2050. if (Width is Dim.DimCombine || Width is Dim.DimView || Width is Dim.DimFill) {
  2051. // It's a Dim.DimCombine and so can't be assigned. Let it have it's width anchored.
  2052. w = Width.Anchor (w);
  2053. canSetWidth = false;
  2054. } else if (Width is Dim.DimFactor factor) {
  2055. // Tries to get the SuperView width otherwise the view width.
  2056. var sw = SuperView != null ? SuperView.Frame.Width : w;
  2057. if (factor.IsFromRemaining ()) {
  2058. sw -= Frame.X;
  2059. }
  2060. w = Width.Anchor (sw);
  2061. canSetWidth = false;
  2062. } else {
  2063. canSetWidth = true;
  2064. }
  2065. resultWidth = w;
  2066. return canSetWidth;
  2067. }
  2068. bool CanSetHeight (int desiredHeight, out int resultHeight)
  2069. {
  2070. int h = desiredHeight;
  2071. bool canSetHeight;
  2072. if (Height is Dim.DimCombine || Height is Dim.DimView || Height is Dim.DimFill) {
  2073. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  2074. h = Height.Anchor (h);
  2075. canSetHeight = false;
  2076. } else if (Height is Dim.DimFactor factor) {
  2077. // Tries to get the SuperView height otherwise the view height.
  2078. var sh = SuperView != null ? SuperView.Frame.Height : h;
  2079. if (factor.IsFromRemaining ()) {
  2080. sh -= Frame.Y;
  2081. }
  2082. h = Height.Anchor (sh);
  2083. canSetHeight = false;
  2084. } else {
  2085. canSetHeight = true;
  2086. }
  2087. resultHeight = h;
  2088. return canSetHeight;
  2089. }
  2090. /// <summary>
  2091. /// Calculate the width based on the <see cref="Width"/> settings.
  2092. /// </summary>
  2093. /// <param name="desiredWidth">The desired width.</param>
  2094. /// <param name="resultWidth">The real result width.</param>
  2095. /// <returns><c>true</c> if the width can be directly assigned, <c>false</c> otherwise.</returns>
  2096. public bool SetWidth (int desiredWidth, out int resultWidth)
  2097. {
  2098. return CanSetWidth (desiredWidth, out resultWidth);
  2099. }
  2100. /// <summary>
  2101. /// Calculate the height based on the <see cref="Height"/> settings.
  2102. /// </summary>
  2103. /// <param name="desiredHeight">The desired height.</param>
  2104. /// <param name="resultHeight">The real result height.</param>
  2105. /// <returns><c>true</c> if the height can be directly assigned, <c>false</c> otherwise.</returns>
  2106. public bool SetHeight (int desiredHeight, out int resultHeight)
  2107. {
  2108. return CanSetHeight (desiredHeight, out resultHeight);
  2109. }
  2110. /// <summary>
  2111. /// Gets the current width based on the <see cref="Width"/> settings.
  2112. /// </summary>
  2113. /// <param name="currentWidth">The real current width.</param>
  2114. /// <returns><c>true</c> if the width can be directly assigned, <c>false</c> otherwise.</returns>
  2115. public bool GetCurrentWidth (out int currentWidth)
  2116. {
  2117. SetRelativeLayout (SuperView == null ? Frame : SuperView.Frame);
  2118. currentWidth = Frame.Width;
  2119. return CanSetWidth (0, out _);
  2120. }
  2121. /// <summary>
  2122. /// Calculate the height based on the <see cref="Height"/> settings.
  2123. /// </summary>
  2124. /// <param name="currentHeight">The real current height.</param>
  2125. /// <returns><c>true</c> if the height can be directly assigned, <c>false</c> otherwise.</returns>
  2126. public bool GetCurrentHeight (out int currentHeight)
  2127. {
  2128. SetRelativeLayout (SuperView == null ? Frame : SuperView.Frame);
  2129. currentHeight = Frame.Height;
  2130. return CanSetHeight (0, out _);
  2131. }
  2132. }
  2133. }