View.cs 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008
  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. ShortcutHelper shortcutHelper;
  122. /// <summary>
  123. /// Event fired when a subview is being added to this view.
  124. /// </summary>
  125. public event Action<View> Added;
  126. /// <summary>
  127. /// Event fired when a subview is being removed from this view.
  128. /// </summary>
  129. public event Action<View> Removed;
  130. /// <summary>
  131. /// Event fired when the view gets focus.
  132. /// </summary>
  133. public event Action<FocusEventArgs> Enter;
  134. /// <summary>
  135. /// Event fired when the view looses focus.
  136. /// </summary>
  137. public event Action<FocusEventArgs> Leave;
  138. /// <summary>
  139. /// Event fired when the view receives the mouse event for the first time.
  140. /// </summary>
  141. public event Action<MouseEventArgs> MouseEnter;
  142. /// <summary>
  143. /// Event fired when the view receives a mouse event for the last time.
  144. /// </summary>
  145. public event Action<MouseEventArgs> MouseLeave;
  146. /// <summary>
  147. /// Event fired when a mouse event is generated.
  148. /// </summary>
  149. public event Action<MouseEventArgs> MouseClick;
  150. /// <summary>
  151. /// Event fired when the <see cref="CanFocus"/> value is being changed.
  152. /// </summary>
  153. public event Action CanFocusChanged;
  154. /// <summary>
  155. /// Event fired when the <see cref="Enabled"/> value is being changed.
  156. /// </summary>
  157. public event Action EnabledChanged;
  158. /// <summary>
  159. /// Event fired when the <see cref="Visible"/> value is being changed.
  160. /// </summary>
  161. public event Action VisibleChanged;
  162. /// <summary>
  163. /// Event invoked when the <see cref="HotKey"/> is changed.
  164. /// </summary>
  165. public event Action<Key> HotKeyChanged;
  166. Key hotKey = Key.Null;
  167. /// <summary>
  168. /// 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.
  169. /// </summary>
  170. public virtual Key HotKey {
  171. get => hotKey;
  172. set {
  173. hotKey = TextFormatter.HotKey = value;
  174. }
  175. }
  176. /// <summary>
  177. /// 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'.
  178. /// </summary>
  179. public virtual Rune HotKeySpecifier {
  180. get => TextFormatter.HotKeySpecifier;
  181. set {
  182. TextFormatter.HotKeySpecifier = value;
  183. SetHotKey ();
  184. }
  185. }
  186. /// <summary>
  187. /// This is the global setting that can be used as a global shortcut to invoke an action if provided.
  188. /// </summary>
  189. public Key Shortcut {
  190. get => shortcutHelper.Shortcut;
  191. set {
  192. if (shortcutHelper.Shortcut != value && (ShortcutHelper.PostShortcutValidation (value) || value == Key.Null)) {
  193. shortcutHelper.Shortcut = value;
  194. }
  195. }
  196. }
  197. /// <summary>
  198. /// The keystroke combination used in the <see cref="Shortcut"/> as string.
  199. /// </summary>
  200. public ustring ShortcutTag => ShortcutHelper.GetShortcutTag (shortcutHelper.Shortcut);
  201. /// <summary>
  202. /// The action to run if the <see cref="Shortcut"/> is defined.
  203. /// </summary>
  204. public virtual Action ShortcutAction { get; set; }
  205. /// <summary>
  206. /// Gets or sets arbitrary data for the view.
  207. /// </summary>
  208. /// <remarks>This property is not used internally.</remarks>
  209. public object Data { get; set; }
  210. internal Direction FocusDirection {
  211. get => SuperView?.FocusDirection ?? focusDirection;
  212. set {
  213. if (SuperView != null)
  214. SuperView.FocusDirection = value;
  215. else
  216. focusDirection = value;
  217. }
  218. }
  219. /// <summary>
  220. /// Points to the current driver in use by the view, it is a convenience property
  221. /// for simplifying the development of new views.
  222. /// </summary>
  223. public static ConsoleDriver Driver { get { return Application.Driver; } }
  224. static IList<View> empty = new List<View> (0).AsReadOnly ();
  225. // This is null, and allocated on demand.
  226. List<View> subviews;
  227. /// <summary>
  228. /// This returns a list of the subviews contained by this view.
  229. /// </summary>
  230. /// <value>The subviews.</value>
  231. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  232. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  233. // to make the same mistakes our users make when they poke at the Subviews.
  234. internal IList<View> InternalSubviews => subviews ?? empty;
  235. // This is null, and allocated on demand.
  236. List<View> tabIndexes;
  237. /// <summary>
  238. /// Configurable keybindings supported by the control
  239. /// </summary>
  240. private Dictionary<Key, Command> KeyBindings { get; set; } = new Dictionary<Key, Command> ();
  241. private Dictionary<Command, Func<bool?>> CommandImplementations { get; set; } = new Dictionary<Command, Func<bool?>> ();
  242. /// <summary>
  243. /// This returns a tab index list of the subviews contained by this view.
  244. /// </summary>
  245. /// <value>The tabIndexes.</value>
  246. public IList<View> TabIndexes => tabIndexes == null ? empty : tabIndexes.AsReadOnly ();
  247. int tabIndex = -1;
  248. /// <summary>
  249. /// Indicates the index of the current <see cref="View"/> from the <see cref="TabIndexes"/> list.
  250. /// </summary>
  251. public int TabIndex {
  252. get { return tabIndex; }
  253. set {
  254. if (!CanFocus) {
  255. tabIndex = -1;
  256. return;
  257. } else if (SuperView?.tabIndexes == null || SuperView?.tabIndexes.Count == 1) {
  258. tabIndex = 0;
  259. return;
  260. } else if (tabIndex == value) {
  261. return;
  262. }
  263. tabIndex = value > SuperView.tabIndexes.Count - 1 ? SuperView.tabIndexes.Count - 1 : value < 0 ? 0 : value;
  264. tabIndex = GetTabIndex (tabIndex);
  265. if (SuperView.tabIndexes.IndexOf (this) != tabIndex) {
  266. SuperView.tabIndexes.Remove (this);
  267. SuperView.tabIndexes.Insert (tabIndex, this);
  268. SetTabIndex ();
  269. }
  270. }
  271. }
  272. int GetTabIndex (int idx)
  273. {
  274. int i = 0;
  275. foreach (var v in SuperView.tabIndexes) {
  276. if (v.tabIndex == -1 || v == this) {
  277. continue;
  278. }
  279. i++;
  280. }
  281. return Math.Min (i, idx);
  282. }
  283. void SetTabIndex ()
  284. {
  285. int i = 0;
  286. foreach (var v in SuperView.tabIndexes) {
  287. if (v.tabIndex == -1) {
  288. continue;
  289. }
  290. v.tabIndex = i;
  291. i++;
  292. }
  293. }
  294. bool tabStop = true;
  295. /// <summary>
  296. /// 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>
  297. /// </summary>
  298. public bool TabStop {
  299. get { return tabStop; }
  300. set {
  301. if (tabStop == value) {
  302. return;
  303. }
  304. tabStop = CanFocus && value;
  305. }
  306. }
  307. bool oldCanFocus;
  308. int oldTabIndex;
  309. /// <inheritdoc/>
  310. public override bool CanFocus {
  311. get => base.CanFocus;
  312. set {
  313. if (!addingView && IsInitialized && SuperView?.CanFocus == false && value) {
  314. throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
  315. }
  316. if (base.CanFocus != value) {
  317. base.CanFocus = value;
  318. if (!value && tabIndex > -1) {
  319. TabIndex = -1;
  320. }
  321. if (value && SuperView?.CanFocus == false && addingView) {
  322. SuperView.CanFocus = value;
  323. }
  324. if (value && tabIndex == -1) {
  325. TabIndex = SuperView != null ? SuperView.tabIndexes.IndexOf (this) : -1;
  326. }
  327. TabStop = value;
  328. if (!value && SuperView?.Focused == this) {
  329. SuperView.focused = null;
  330. }
  331. if (!value && HasFocus) {
  332. SetHasFocus (false, this);
  333. SuperView?.EnsureFocus ();
  334. if (SuperView != null && SuperView?.Focused == null) {
  335. SuperView.FocusNext ();
  336. if (SuperView.Focused == null) {
  337. Application.Current.FocusNext ();
  338. }
  339. Application.EnsuresTopOnFront ();
  340. }
  341. }
  342. if (subviews != null && IsInitialized) {
  343. foreach (var view in subviews) {
  344. if (view.CanFocus != value) {
  345. if (!value) {
  346. view.oldCanFocus = view.CanFocus;
  347. view.oldTabIndex = view.tabIndex;
  348. view.CanFocus = value;
  349. view.tabIndex = -1;
  350. } else {
  351. if (addingView) {
  352. view.addingView = true;
  353. }
  354. view.CanFocus = view.oldCanFocus;
  355. view.tabIndex = view.oldTabIndex;
  356. view.addingView = false;
  357. }
  358. }
  359. }
  360. }
  361. OnCanFocusChanged ();
  362. SetNeedsDisplay ();
  363. }
  364. }
  365. }
  366. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  367. // The frame for the object. Superview relative.
  368. Rect frame;
  369. /// <summary>
  370. /// Gets or sets an identifier for the view;
  371. /// </summary>
  372. /// <value>The identifier.</value>
  373. /// <remarks>The id should be unique across all Views that share a SuperView.</remarks>
  374. public ustring Id { get; set; } = "";
  375. /// <summary>
  376. /// Returns a value indicating if this View is currently on Top (Active)
  377. /// </summary>
  378. public bool IsCurrentTop {
  379. get {
  380. return Application.Current == this;
  381. }
  382. }
  383. /// <summary>
  384. /// Gets or sets a value indicating whether this <see cref="View"/> wants mouse position reports.
  385. /// </summary>
  386. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  387. public virtual bool WantMousePositionReports { get; set; } = false;
  388. /// <summary>
  389. /// Gets or sets a value indicating whether this <see cref="View"/> want continuous button pressed event.
  390. /// </summary>
  391. public virtual bool WantContinuousButtonPressed { get; set; } = false;
  392. /// <summary>
  393. /// Gets or sets the frame for the view. The frame is relative to the view's container (<see cref="SuperView"/>).
  394. /// </summary>
  395. /// <value>The frame.</value>
  396. /// <remarks>
  397. /// <para>
  398. /// Change the Frame when using the <see cref="LayoutStyle.Absolute"/> layout style to move or resize views.
  399. /// </para>
  400. /// <para>
  401. /// Altering the Frame of a view will trigger the redrawing of the
  402. /// view as well as the redrawing of the affected regions of the <see cref="SuperView"/>.
  403. /// </para>
  404. /// </remarks>
  405. public virtual Rect Frame {
  406. get => frame;
  407. set {
  408. if (SuperView != null) {
  409. SuperView.SetNeedsDisplay (frame);
  410. SuperView.SetNeedsDisplay (value);
  411. }
  412. frame = new Rect (value.X, value.Y, Math.Max (value.Width, 0), Math.Max (value.Height, 0));
  413. TextFormatter.Size = GetBoundsTextFormatterSize ();
  414. SetNeedsLayout ();
  415. SetNeedsDisplay (frame);
  416. }
  417. }
  418. ///// <summary>
  419. ///// Gets an enumerator that enumerates the subviews in this view.
  420. ///// </summary>
  421. ///// <returns>The enumerator.</returns>
  422. //public IEnumerator GetEnumerator ()
  423. //{
  424. // foreach (var v in InternalSubviews)
  425. // yield return v;
  426. //}
  427. LayoutStyle layoutStyle;
  428. /// <summary>
  429. /// Controls how the View's <see cref="Frame"/> is computed during the LayoutSubviews method, if the style is set to <see cref="LayoutStyle.Absolute"/>,
  430. /// LayoutSubviews does not change the <see cref="Frame"/>. If the style is <see cref="LayoutStyle.Computed"/> the <see cref="Frame"/> is updated using
  431. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  432. /// </summary>
  433. /// <value>The layout style.</value>
  434. public LayoutStyle LayoutStyle {
  435. get => layoutStyle;
  436. set {
  437. layoutStyle = value;
  438. SetNeedsLayout ();
  439. }
  440. }
  441. /// <summary>
  442. /// The bounds represent the View-relative rectangle used for this view; the area inside of the view.
  443. /// </summary>
  444. /// <value>The bounds.</value>
  445. /// <remarks>
  446. /// <para>
  447. /// Updates to the Bounds update the <see cref="Frame"/>,
  448. /// and has the same side effects as updating the <see cref="Frame"/>.
  449. /// </para>
  450. /// <para>
  451. /// Because <see cref="Bounds"/> coordinates are relative to the upper-left corner of the <see cref="View"/>,
  452. /// the coordinates of the upper-left corner of the rectangle returned by this property are (0,0).
  453. /// Use this property to obtain the size and coordinates of the client area of the
  454. /// control for tasks such as drawing on the surface of the control.
  455. /// </para>
  456. /// </remarks>
  457. public Rect Bounds {
  458. get => new Rect (Point.Empty, Frame.Size);
  459. set {
  460. Frame = new Rect (frame.Location, value.Size);
  461. }
  462. }
  463. Pos x, y;
  464. /// <summary>
  465. /// Gets or sets the X position for the view (the column). Only used the <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  466. /// </summary>
  467. /// <value>The X Position.</value>
  468. /// <remarks>
  469. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  470. /// </remarks>
  471. public Pos X {
  472. get => x;
  473. set {
  474. if (ForceValidatePosDim && !ValidatePosDim (x, value)) {
  475. throw new ArgumentException ();
  476. }
  477. x = value;
  478. ProcessResizeView ();
  479. }
  480. }
  481. /// <summary>
  482. /// Gets or sets the Y position for the view (the row). Only used the <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  483. /// </summary>
  484. /// <value>The y position (line).</value>
  485. /// <remarks>
  486. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  487. /// </remarks>
  488. public Pos Y {
  489. get => y;
  490. set {
  491. if (ForceValidatePosDim && !ValidatePosDim (y, value)) {
  492. throw new ArgumentException ();
  493. }
  494. y = value;
  495. ProcessResizeView ();
  496. }
  497. }
  498. Dim width, height;
  499. /// <summary>
  500. /// Gets or sets the width of the view. Only used the <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  501. /// </summary>
  502. /// <value>The width.</value>
  503. /// <remarks>
  504. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  505. /// </remarks>
  506. public Dim Width {
  507. get => width;
  508. set {
  509. if (ForceValidatePosDim && !ValidatePosDim (width, value)) {
  510. throw new ArgumentException ("ForceValidatePosDim is enabled", nameof (Width));
  511. }
  512. width = value;
  513. if (ForceValidatePosDim) {
  514. var isValidNewAutSize = autoSize && IsValidAutoSizeWidth (width);
  515. if (IsAdded && autoSize && !isValidNewAutSize) {
  516. throw new InvalidOperationException ("Must set AutoSize to false before set the Width.");
  517. }
  518. }
  519. ProcessResizeView ();
  520. }
  521. }
  522. /// <summary>
  523. /// Gets or sets the height of the view. Only used the <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Computed"/>.
  524. /// </summary>
  525. /// <value>The height.</value>
  526. /// If <see cref="LayoutStyle"/> is <see cref="LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  527. public Dim Height {
  528. get => height;
  529. set {
  530. if (ForceValidatePosDim && !ValidatePosDim (height, value)) {
  531. throw new ArgumentException ("ForceValidatePosDim is enabled", nameof (Height));
  532. }
  533. height = value;
  534. if (ForceValidatePosDim) {
  535. var isValidNewAutSize = autoSize && IsValidAutoSizeHeight (height);
  536. if (IsAdded && autoSize && !isValidNewAutSize) {
  537. throw new InvalidOperationException ("Must set AutoSize to false before set the Height.");
  538. }
  539. }
  540. ProcessResizeView ();
  541. }
  542. }
  543. /// <summary>
  544. /// Forces validation with <see cref="LayoutStyle.Computed"/> layout
  545. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  546. /// </summary>
  547. public bool ForceValidatePosDim { get; set; }
  548. bool ValidatePosDim (object oldvalue, object newValue)
  549. {
  550. if (!IsInitialized || layoutStyle == LayoutStyle.Absolute || oldvalue == null || oldvalue.GetType () == newValue.GetType () || this is Toplevel) {
  551. return true;
  552. }
  553. if (layoutStyle == LayoutStyle.Computed) {
  554. if (oldvalue.GetType () != newValue.GetType () && !(newValue is Pos.PosAbsolute || newValue is Dim.DimAbsolute)) {
  555. return true;
  556. }
  557. }
  558. return false;
  559. }
  560. /// <summary>
  561. /// Verifies if the minimum width or height can be sets in the view.
  562. /// </summary>
  563. /// <param name="size">The size.</param>
  564. /// <returns><see langword="true"/> if the size can be set, <see langword="false"/>otherwise.</returns>
  565. public bool GetMinWidthHeight (out Size size)
  566. {
  567. size = Size.Empty;
  568. if (!AutoSize && !ustring.IsNullOrEmpty (TextFormatter.Text)) {
  569. switch (TextFormatter.IsVerticalDirection (TextDirection)) {
  570. case true:
  571. var colWidth = TextFormatter.GetSumMaxCharWidth (new List<ustring> { TextFormatter.Text }, 0, 1);
  572. if (frame.Width < colWidth && (Width == null || (Bounds.Width >= 0 && Width is Dim.DimAbsolute
  573. && Width.Anchor (0) >= 0 && Width.Anchor (0) < colWidth))) {
  574. size = new Size (colWidth, Bounds.Height);
  575. return true;
  576. }
  577. break;
  578. default:
  579. if (frame.Height < 1 && (Height == null || (Height is Dim.DimAbsolute && Height.Anchor (0) == 0))) {
  580. size = new Size (Bounds.Width, 1);
  581. return true;
  582. }
  583. break;
  584. }
  585. }
  586. return false;
  587. }
  588. /// <summary>
  589. /// Sets the minimum width or height if the view can be resized.
  590. /// </summary>
  591. /// <returns><see langword="true"/> if the size can be set, <see langword="false"/>otherwise.</returns>
  592. public bool SetMinWidthHeight ()
  593. {
  594. if (GetMinWidthHeight (out Size size)) {
  595. Bounds = new Rect (Bounds.Location, size);
  596. TextFormatter.Size = GetBoundsTextFormatterSize ();
  597. return true;
  598. }
  599. return false;
  600. }
  601. /// <summary>
  602. /// Gets or sets the <see cref="Terminal.Gui.TextFormatter"/> which can be handled differently by any derived class.
  603. /// </summary>
  604. public TextFormatter TextFormatter { get; set; }
  605. /// <summary>
  606. /// Returns the container for this view, or null if this view has not been added to a container.
  607. /// </summary>
  608. /// <value>The super view.</value>
  609. public View SuperView => container;
  610. /// <summary>
  611. /// Initializes a new instance of a <see cref="LayoutStyle.Absolute"/> <see cref="View"/> class with the absolute
  612. /// dimensions specified in the <c>frame</c> parameter.
  613. /// </summary>
  614. /// <param name="frame">The region covered by this view.</param>
  615. /// <remarks>
  616. /// This constructor initialize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Absolute"/>. Use <see cref="View()"/> to
  617. /// initialize a View with <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>
  618. /// </remarks>
  619. public View (Rect frame)
  620. {
  621. Initialize (ustring.Empty, frame, LayoutStyle.Absolute, TextDirection.LeftRight_TopBottom);
  622. }
  623. /// <summary>
  624. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  625. /// </summary>
  626. /// <remarks>
  627. /// <para>
  628. /// 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.
  629. /// The <see cref="Label"/> will be created using <see cref="LayoutStyle.Computed"/>
  630. /// coordinates. The initial size (<see cref="View.Frame"/> will be
  631. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  632. /// </para>
  633. /// <para>
  634. /// If <c>Height</c> is greater than one, word wrapping is provided.
  635. /// </para>
  636. /// <para>
  637. /// This constructor initialize a View with a <see cref="LayoutStyle"/> of <see cref="LayoutStyle.Computed"/>.
  638. /// 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.
  639. /// </para>
  640. /// </remarks>
  641. public View () : this (text: string.Empty, direction: TextDirection.LeftRight_TopBottom) { }
  642. /// <summary>
  643. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  644. /// </summary>
  645. /// <remarks>
  646. /// <para>
  647. /// The <see cref="View"/> will be created at the given
  648. /// coordinates with the given string. The size (<see cref="View.Frame"/> will be
  649. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  650. /// </para>
  651. /// <para>
  652. /// No line wrapping is provided.
  653. /// </para>
  654. /// </remarks>
  655. /// <param name="x">column to locate the Label.</param>
  656. /// <param name="y">row to locate the Label.</param>
  657. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  658. public View (int x, int y, ustring text) : this (TextFormatter.CalcRect (x, y, text), text) { }
  659. /// <summary>
  660. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Absolute"/> layout.
  661. /// </summary>
  662. /// <remarks>
  663. /// <para>
  664. /// The <see cref="View"/> will be created at the given
  665. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  666. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  667. /// </para>
  668. /// <para>
  669. /// If <c>rect.Height</c> is greater than one, word wrapping is provided.
  670. /// </para>
  671. /// </remarks>
  672. /// <param name="rect">Location.</param>
  673. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  674. /// <param name="border">The <see cref="Border"/>.</param>
  675. public View (Rect rect, ustring text, Border border = null)
  676. {
  677. Initialize (text, rect, LayoutStyle.Absolute, TextDirection.LeftRight_TopBottom, border);
  678. }
  679. /// <summary>
  680. /// Initializes a new instance of <see cref="View"/> using <see cref="LayoutStyle.Computed"/> layout.
  681. /// </summary>
  682. /// <remarks>
  683. /// <para>
  684. /// The <see cref="View"/> will be created using <see cref="LayoutStyle.Computed"/>
  685. /// coordinates with the given string. The initial size (<see cref="View.Frame"/> will be
  686. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  687. /// </para>
  688. /// <para>
  689. /// If <c>Height</c> is greater than one, word wrapping is provided.
  690. /// </para>
  691. /// </remarks>
  692. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  693. /// <param name="direction">The text direction.</param>
  694. /// <param name="border">The <see cref="Border"/>.</param>
  695. public View (ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom, Border border = null)
  696. {
  697. Initialize (text, Rect.Empty, LayoutStyle.Computed, direction, border);
  698. }
  699. void Initialize (ustring text, Rect rect, LayoutStyle layoutStyle = LayoutStyle.Computed,
  700. TextDirection direction = TextDirection.LeftRight_TopBottom, Border border = null)
  701. {
  702. TextFormatter = new TextFormatter ();
  703. TextFormatter.HotKeyChanged += TextFormatter_HotKeyChanged;
  704. TextDirection = direction;
  705. Border = border;
  706. if (Border != null) {
  707. Border.Child = this;
  708. }
  709. shortcutHelper = new ShortcutHelper ();
  710. CanFocus = false;
  711. TabIndex = -1;
  712. TabStop = false;
  713. LayoutStyle = layoutStyle;
  714. // BUGBUG: CalcRect doesn't account for line wrapping
  715. Rect r;
  716. if (rect.IsEmpty) {
  717. r = TextFormatter.CalcRect (0, 0, text, direction);
  718. } else {
  719. r = rect;
  720. }
  721. Frame = r;
  722. Text = text;
  723. UpdateTextFormatterText ();
  724. ProcessResizeView ();
  725. }
  726. /// <summary>
  727. /// Can be overridden if the <see cref="TextFormatter.Text"/> has
  728. /// different format than the default.
  729. /// </summary>
  730. protected virtual void UpdateTextFormatterText ()
  731. {
  732. TextFormatter.Text = text;
  733. }
  734. /// <summary>
  735. /// Can be overridden if the view resize behavior is
  736. /// different than the default.
  737. /// </summary>
  738. protected virtual void ProcessResizeView ()
  739. {
  740. var _x = x is Pos.PosAbsolute ? x.Anchor (0) : frame.X;
  741. var _y = y is Pos.PosAbsolute ? y.Anchor (0) : frame.Y;
  742. if (AutoSize) {
  743. var s = CalculateAutoSize ();
  744. var w = width is Dim.DimAbsolute && width.Anchor (0) > s.Width ? width.Anchor (0) : s.Width;
  745. var h = height is Dim.DimAbsolute && height.Anchor (0) > s.Height ? height.Anchor (0) : s.Height;
  746. frame = new Rect (new Point (_x, _y), new Size (w, h));
  747. } else {
  748. var w = width is Dim.DimAbsolute ? width.Anchor (0) : frame.Width;
  749. var h = height is Dim.DimAbsolute ? height.Anchor (0) : frame.Height;
  750. frame = new Rect (new Point (_x, _y), new Size (w, h));
  751. SetMinWidthHeight ();
  752. }
  753. TextFormatter.Size = GetBoundsTextFormatterSize ();
  754. SetNeedsLayout ();
  755. SetNeedsDisplay ();
  756. }
  757. private void TextFormatter_HotKeyChanged (Key obj)
  758. {
  759. HotKeyChanged?.Invoke (obj);
  760. }
  761. /// <summary>
  762. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  763. /// </summary>
  764. public void SetNeedsDisplay ()
  765. {
  766. SetNeedsDisplay (Bounds);
  767. }
  768. internal bool LayoutNeeded { get; private set; } = true;
  769. internal void SetNeedsLayout ()
  770. {
  771. if (LayoutNeeded)
  772. return;
  773. LayoutNeeded = true;
  774. if (SuperView == null)
  775. return;
  776. SuperView.SetNeedsLayout ();
  777. foreach (var view in Subviews) {
  778. view.SetNeedsLayout ();
  779. }
  780. TextFormatter.NeedsFormat = true;
  781. }
  782. /// <summary>
  783. /// Removes the <see cref="SetNeedsLayout"/> setting on this view.
  784. /// </summary>
  785. protected void ClearLayoutNeeded ()
  786. {
  787. LayoutNeeded = false;
  788. }
  789. /// <summary>
  790. /// Flags the view-relative region on this View as needing to be repainted.
  791. /// </summary>
  792. /// <param name="region">The view-relative region that must be flagged for repaint.</param>
  793. public void SetNeedsDisplay (Rect region)
  794. {
  795. if (NeedDisplay.IsEmpty)
  796. NeedDisplay = region;
  797. else {
  798. var x = Math.Min (NeedDisplay.X, region.X);
  799. var y = Math.Min (NeedDisplay.Y, region.Y);
  800. var w = Math.Max (NeedDisplay.Width, region.Width);
  801. var h = Math.Max (NeedDisplay.Height, region.Height);
  802. NeedDisplay = new Rect (x, y, w, h);
  803. }
  804. if (container != null)
  805. container.SetChildNeedsDisplay ();
  806. if (subviews == null)
  807. return;
  808. foreach (var view in subviews)
  809. if (view.Frame.IntersectsWith (region)) {
  810. var childRegion = Rect.Intersect (view.Frame, region);
  811. childRegion.X -= view.Frame.X;
  812. childRegion.Y -= view.Frame.Y;
  813. view.SetNeedsDisplay (childRegion);
  814. }
  815. }
  816. internal bool ChildNeedsDisplay { get; private set; }
  817. /// <summary>
  818. /// Indicates that any child views (in the <see cref="Subviews"/> list) need to be repainted.
  819. /// </summary>
  820. public void SetChildNeedsDisplay ()
  821. {
  822. ChildNeedsDisplay = true;
  823. if (container != null)
  824. container.SetChildNeedsDisplay ();
  825. }
  826. internal bool addingView = false;
  827. /// <summary>
  828. /// Adds a subview (child) to this view.
  829. /// </summary>
  830. /// <remarks>
  831. /// 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"/>
  832. /// </remarks>
  833. public virtual void Add (View view)
  834. {
  835. if (view == null)
  836. return;
  837. if (subviews == null) {
  838. subviews = new List<View> ();
  839. }
  840. if (tabIndexes == null) {
  841. tabIndexes = new List<View> ();
  842. }
  843. subviews.Add (view);
  844. tabIndexes.Add (view);
  845. view.container = this;
  846. if (view.CanFocus) {
  847. addingView = true;
  848. if (SuperView?.CanFocus == false) {
  849. SuperView.addingView = true;
  850. SuperView.CanFocus = true;
  851. SuperView.addingView = false;
  852. }
  853. CanFocus = true;
  854. view.tabIndex = tabIndexes.IndexOf (view);
  855. addingView = false;
  856. }
  857. SetNeedsLayout ();
  858. SetNeedsDisplay ();
  859. OnAdded (view);
  860. if (IsInitialized) {
  861. view.BeginInit ();
  862. view.EndInit ();
  863. }
  864. }
  865. /// <summary>
  866. /// Adds the specified views (children) to the view.
  867. /// </summary>
  868. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  869. /// <remarks>
  870. /// 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"/>
  871. /// </remarks>
  872. public void Add (params View [] views)
  873. {
  874. if (views == null)
  875. return;
  876. foreach (var view in views)
  877. Add (view);
  878. }
  879. /// <summary>
  880. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  881. /// </summary>
  882. public virtual void RemoveAll ()
  883. {
  884. if (subviews == null)
  885. return;
  886. while (subviews.Count > 0) {
  887. Remove (subviews [0]);
  888. }
  889. }
  890. /// <summary>
  891. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  892. /// </summary>
  893. /// <remarks>
  894. /// </remarks>
  895. public virtual void Remove (View view)
  896. {
  897. if (view == null || subviews == null)
  898. return;
  899. SetNeedsLayout ();
  900. SetNeedsDisplay ();
  901. var touched = view.Frame;
  902. subviews.Remove (view);
  903. tabIndexes.Remove (view);
  904. view.container = null;
  905. view.tabIndex = -1;
  906. if (subviews.Count < 1) {
  907. CanFocus = false;
  908. }
  909. foreach (var v in subviews) {
  910. if (v.Frame.IntersectsWith (touched))
  911. view.SetNeedsDisplay ();
  912. }
  913. OnRemoved (view);
  914. if (focused == view) {
  915. focused = null;
  916. }
  917. }
  918. void PerformActionForSubview (View subview, Action<View> action)
  919. {
  920. if (subviews.Contains (subview)) {
  921. action (subview);
  922. }
  923. SetNeedsDisplay ();
  924. subview.SetNeedsDisplay ();
  925. }
  926. /// <summary>
  927. /// Brings the specified subview to the front so it is drawn on top of any other views.
  928. /// </summary>
  929. /// <param name="subview">The subview to send to the front</param>
  930. /// <remarks>
  931. /// <seealso cref="SendSubviewToBack"/>.
  932. /// </remarks>
  933. public void BringSubviewToFront (View subview)
  934. {
  935. PerformActionForSubview (subview, x => {
  936. subviews.Remove (x);
  937. subviews.Add (x);
  938. });
  939. }
  940. /// <summary>
  941. /// Sends the specified subview to the front so it is the first view drawn
  942. /// </summary>
  943. /// <param name="subview">The subview to send to the front</param>
  944. /// <remarks>
  945. /// <seealso cref="BringSubviewToFront(View)"/>.
  946. /// </remarks>
  947. public void SendSubviewToBack (View subview)
  948. {
  949. PerformActionForSubview (subview, x => {
  950. subviews.Remove (x);
  951. subviews.Insert (0, subview);
  952. });
  953. }
  954. /// <summary>
  955. /// Moves the subview backwards in the hierarchy, only one step
  956. /// </summary>
  957. /// <param name="subview">The subview to send backwards</param>
  958. /// <remarks>
  959. /// If you want to send the view all the way to the back use SendSubviewToBack.
  960. /// </remarks>
  961. public void SendSubviewBackwards (View subview)
  962. {
  963. PerformActionForSubview (subview, x => {
  964. var idx = subviews.IndexOf (x);
  965. if (idx > 0) {
  966. subviews.Remove (x);
  967. subviews.Insert (idx - 1, x);
  968. }
  969. });
  970. }
  971. /// <summary>
  972. /// Moves the subview backwards in the hierarchy, only one step
  973. /// </summary>
  974. /// <param name="subview">The subview to send backwards</param>
  975. /// <remarks>
  976. /// If you want to send the view all the way to the back use SendSubviewToBack.
  977. /// </remarks>
  978. public void BringSubviewForward (View subview)
  979. {
  980. PerformActionForSubview (subview, x => {
  981. var idx = subviews.IndexOf (x);
  982. if (idx + 1 < subviews.Count) {
  983. subviews.Remove (x);
  984. subviews.Insert (idx + 1, x);
  985. }
  986. });
  987. }
  988. /// <summary>
  989. /// Clears the view region with the current color.
  990. /// </summary>
  991. /// <remarks>
  992. /// <para>
  993. /// This clears the entire region used by this view.
  994. /// </para>
  995. /// </remarks>
  996. public void Clear ()
  997. {
  998. var h = Frame.Height;
  999. var w = Frame.Width;
  1000. for (int line = 0; line < h; line++) {
  1001. Move (0, line);
  1002. for (int col = 0; col < w; col++)
  1003. Driver.AddRune (' ');
  1004. }
  1005. }
  1006. /// <summary>
  1007. /// Clears the specified region with the current color.
  1008. /// </summary>
  1009. /// <remarks>
  1010. /// </remarks>
  1011. /// <param name="regionScreen">The screen-relative region to clear.</param>
  1012. public void Clear (Rect regionScreen)
  1013. {
  1014. var h = regionScreen.Height;
  1015. var w = regionScreen.Width;
  1016. for (int line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  1017. Driver.Move (regionScreen.X, line);
  1018. for (int col = 0; col < w; col++)
  1019. Driver.AddRune (' ');
  1020. }
  1021. }
  1022. /// <summary>
  1023. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  1024. /// </summary>
  1025. /// <param name="col">View-relative column.</param>
  1026. /// <param name="row">View-relative row.</param>
  1027. /// <param name="rcol">Absolute column; screen-relative.</param>
  1028. /// <param name="rrow">Absolute row; screen-relative.</param>
  1029. /// <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>
  1030. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  1031. {
  1032. // Computes the real row, col relative to the screen.
  1033. rrow = row + frame.Y;
  1034. rcol = col + frame.X;
  1035. var ccontainer = container;
  1036. while (ccontainer != null) {
  1037. rrow += ccontainer.frame.Y;
  1038. rcol += ccontainer.frame.X;
  1039. ccontainer = ccontainer.container;
  1040. }
  1041. // The following ensures that the cursor is always in the screen boundaries.
  1042. if (clipped) {
  1043. rrow = Math.Min (rrow, Driver.Rows - 1);
  1044. rcol = Math.Min (rcol, Driver.Cols - 1);
  1045. }
  1046. }
  1047. /// <summary>
  1048. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  1049. /// </summary>
  1050. /// <returns>The mapped point.</returns>
  1051. /// <param name="x">X screen-coordinate point.</param>
  1052. /// <param name="y">Y screen-coordinate point.</param>
  1053. public Point ScreenToView (int x, int y)
  1054. {
  1055. if (SuperView == null) {
  1056. return new Point (x - Frame.X, y - frame.Y);
  1057. } else {
  1058. var parent = SuperView.ScreenToView (x, y);
  1059. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  1064. /// </summary>
  1065. internal Rect ViewToScreen (Rect region)
  1066. {
  1067. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  1068. return new Rect (x, y, region.Width, region.Height);
  1069. }
  1070. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  1071. internal Rect ScreenClip (Rect regionScreen)
  1072. {
  1073. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  1074. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  1075. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  1076. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  1077. return new Rect (x, y, w, h);
  1078. }
  1079. /// <summary>
  1080. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  1081. /// </summary>
  1082. /// <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>
  1083. /// <remarks>
  1084. /// <see cref="Bounds"/> is View-relative.
  1085. /// </remarks>
  1086. public Rect ClipToBounds ()
  1087. {
  1088. return SetClip (Bounds);
  1089. }
  1090. /// <summary>
  1091. /// Sets the clip region to the specified view-relative region.
  1092. /// </summary>
  1093. /// <returns>The previous screen-relative clip region.</returns>
  1094. /// <param name="region">View-relative clip region.</param>
  1095. public Rect SetClip (Rect region)
  1096. {
  1097. var previous = Driver.Clip;
  1098. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  1099. return previous;
  1100. }
  1101. /// <summary>
  1102. /// Draws a frame in the current view, clipped by the boundary of this view
  1103. /// </summary>
  1104. /// <param name="region">View-relative region for the frame to be drawn.</param>
  1105. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  1106. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  1107. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  1108. {
  1109. var scrRect = ViewToScreen (region);
  1110. var savedClip = ClipToBounds ();
  1111. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  1112. Driver.Clip = savedClip;
  1113. }
  1114. /// <summary>
  1115. /// Utility function to draw strings that contain a hotkey.
  1116. /// </summary>
  1117. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  1118. /// <param name="hotColor">Hot color.</param>
  1119. /// <param name="normalColor">Normal color.</param>
  1120. /// <remarks>
  1121. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  1122. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  1123. /// </remarks>
  1124. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  1125. {
  1126. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  1127. Application.Driver.SetAttribute (normalColor);
  1128. foreach (var rune in text) {
  1129. if (rune == hotkeySpec) {
  1130. Application.Driver.SetAttribute (hotColor);
  1131. continue;
  1132. }
  1133. Application.Driver.AddRune (rune);
  1134. Application.Driver.SetAttribute (normalColor);
  1135. }
  1136. }
  1137. /// <summary>
  1138. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  1139. /// </summary>
  1140. /// <param name="text">String to display, the underscore before a letter flags the next letter as the hotkey.</param>
  1141. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  1142. /// <param name="scheme">The color scheme to use.</param>
  1143. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  1144. {
  1145. if (focused)
  1146. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  1147. else
  1148. DrawHotString (text, Enabled ? scheme.HotNormal : scheme.Disabled, Enabled ? scheme.Normal : scheme.Disabled);
  1149. }
  1150. /// <summary>
  1151. /// This moves the cursor to the specified column and row in the view.
  1152. /// </summary>
  1153. /// <returns>The move.</returns>
  1154. /// <param name="col">Col.</param>
  1155. /// <param name="row">Row.</param>
  1156. /// <param name="clipped">Whether to clip the result of the ViewToScreen method,
  1157. /// if set to <c>true</c>, the col, row values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).</param>
  1158. public void Move (int col, int row, bool clipped = true)
  1159. {
  1160. if (Driver.Rows == 0) {
  1161. return;
  1162. }
  1163. ViewToScreen (col, row, out var rcol, out var rrow, clipped);
  1164. Driver.Move (rcol, rrow);
  1165. }
  1166. /// <summary>
  1167. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1168. /// </summary>
  1169. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1170. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1171. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1172. /// the last focused view. Views should make sure that they place the cursor
  1173. /// in a visually sensible place.
  1174. public virtual void PositionCursor ()
  1175. {
  1176. if (!CanBeVisible (this) || !Enabled) {
  1177. return;
  1178. }
  1179. if (focused?.Visible == true && focused?.Enabled == true && focused?.Frame.Width > 0 && focused.Frame.Height > 0) {
  1180. focused.PositionCursor ();
  1181. } else {
  1182. if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
  1183. Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
  1184. } else {
  1185. Move (frame.X, frame.Y);
  1186. }
  1187. }
  1188. }
  1189. bool hasFocus;
  1190. /// <inheritdoc/>
  1191. public override bool HasFocus {
  1192. get {
  1193. return hasFocus;
  1194. }
  1195. }
  1196. void SetHasFocus (bool value, View view, bool force = false)
  1197. {
  1198. if (hasFocus != value || force) {
  1199. hasFocus = value;
  1200. if (value) {
  1201. OnEnter (view);
  1202. } else {
  1203. OnLeave (view);
  1204. }
  1205. SetNeedsDisplay ();
  1206. }
  1207. // Remove focus down the chain of subviews if focus is removed
  1208. if (!value && focused != null) {
  1209. focused.OnLeave (view);
  1210. focused.SetHasFocus (false, view);
  1211. focused = null;
  1212. }
  1213. }
  1214. /// <summary>
  1215. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  1216. /// </summary>
  1217. public class FocusEventArgs : EventArgs {
  1218. /// <summary>
  1219. /// Constructs.
  1220. /// </summary>
  1221. /// <param name="view">The view that gets or loses focus.</param>
  1222. public FocusEventArgs (View view) { View = view; }
  1223. /// <summary>
  1224. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  1225. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1226. /// </summary>
  1227. public bool Handled { get; set; }
  1228. /// <summary>
  1229. /// Indicates the current view that gets or loses focus.
  1230. /// </summary>
  1231. public View View { get; set; }
  1232. }
  1233. /// <summary>
  1234. /// Method invoked when a subview is being added to this view.
  1235. /// </summary>
  1236. /// <param name="view">The subview being added.</param>
  1237. public virtual void OnAdded (View view)
  1238. {
  1239. view.IsAdded = true;
  1240. view.x = view.x ?? view.frame.X;
  1241. view.y = view.y ?? view.frame.Y;
  1242. view.width = view.width ?? view.frame.Width;
  1243. view.height = view.height ?? view.frame.Height;
  1244. view.Added?.Invoke (this);
  1245. }
  1246. /// <summary>
  1247. /// Method invoked when a subview is being removed from this view.
  1248. /// </summary>
  1249. /// <param name="view">The subview being removed.</param>
  1250. public virtual void OnRemoved (View view)
  1251. {
  1252. view.IsAdded = false;
  1253. view.Removed?.Invoke (this);
  1254. }
  1255. /// <inheritdoc/>
  1256. public override bool OnEnter (View view)
  1257. {
  1258. FocusEventArgs args = new FocusEventArgs (view);
  1259. Enter?.Invoke (args);
  1260. if (args.Handled)
  1261. return true;
  1262. if (base.OnEnter (view))
  1263. return true;
  1264. return false;
  1265. }
  1266. /// <inheritdoc/>
  1267. public override bool OnLeave (View view)
  1268. {
  1269. FocusEventArgs args = new FocusEventArgs (view);
  1270. Leave?.Invoke (args);
  1271. if (args.Handled)
  1272. return true;
  1273. if (base.OnLeave (view))
  1274. return true;
  1275. return false;
  1276. }
  1277. /// <summary>
  1278. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1279. /// </summary>
  1280. /// <value>The focused.</value>
  1281. public View Focused => focused;
  1282. /// <summary>
  1283. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1284. /// </summary>
  1285. /// <value>The most focused.</value>
  1286. public View MostFocused {
  1287. get {
  1288. if (Focused == null)
  1289. return null;
  1290. var most = Focused.MostFocused;
  1291. if (most != null)
  1292. return most;
  1293. return Focused;
  1294. }
  1295. }
  1296. ColorScheme colorScheme;
  1297. /// <summary>
  1298. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1299. /// color scheme.
  1300. /// </summary>
  1301. public virtual ColorScheme ColorScheme {
  1302. get {
  1303. if (colorScheme == null)
  1304. return SuperView?.ColorScheme;
  1305. return colorScheme;
  1306. }
  1307. set {
  1308. if (colorScheme != value) {
  1309. colorScheme = value;
  1310. SetNeedsDisplay ();
  1311. }
  1312. }
  1313. }
  1314. /// <summary>
  1315. /// Displays the specified character in the specified column and row of the View.
  1316. /// </summary>
  1317. /// <param name="col">Column (view-relative).</param>
  1318. /// <param name="row">Row (view-relative).</param>
  1319. /// <param name="ch">Ch.</param>
  1320. public void AddRune (int col, int row, Rune ch)
  1321. {
  1322. if (row < 0 || col < 0)
  1323. return;
  1324. if (row > frame.Height - 1 || col > frame.Width - 1)
  1325. return;
  1326. Move (col, row);
  1327. Driver.AddRune (ch);
  1328. }
  1329. /// <summary>
  1330. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  1331. /// </summary>
  1332. protected void ClearNeedsDisplay ()
  1333. {
  1334. NeedDisplay = Rect.Empty;
  1335. ChildNeedsDisplay = false;
  1336. }
  1337. /// <summary>
  1338. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1339. /// </summary>
  1340. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1341. /// <remarks>
  1342. /// <para>
  1343. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1344. /// </para>
  1345. /// <para>
  1346. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1347. /// the last color that was set globally on the driver.
  1348. /// </para>
  1349. /// <para>
  1350. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1351. /// larger than the <c>region</c> parameter.
  1352. /// </para>
  1353. /// </remarks>
  1354. public virtual void Redraw (Rect bounds)
  1355. {
  1356. if (!CanBeVisible (this)) {
  1357. return;
  1358. }
  1359. var clipRect = new Rect (Point.Empty, frame.Size);
  1360. //if (ColorScheme != null && !(this is Toplevel)) {
  1361. if (ColorScheme != null) {
  1362. Driver.SetAttribute (HasFocus ? ColorScheme.Focus : ColorScheme.Normal);
  1363. }
  1364. if (Border != null) {
  1365. Border.DrawContent (this);
  1366. }
  1367. if (!ustring.IsNullOrEmpty (TextFormatter.Text) || (this is Label && !AutoSize)) {
  1368. Clear ();
  1369. // Draw any Text
  1370. if (TextFormatter != null) {
  1371. TextFormatter.NeedsFormat = true;
  1372. }
  1373. var containerBounds = SuperView == null ? default : SuperView.ViewToScreen (SuperView.Bounds);
  1374. containerBounds.X = Math.Max (containerBounds.X, Driver.Clip.X);
  1375. containerBounds.Y = Math.Max (containerBounds.Y, Driver.Clip.Y);
  1376. containerBounds.Width = Math.Min (containerBounds.Width, Driver.Clip.Width);
  1377. containerBounds.Height = Math.Min (containerBounds.Height, Driver.Clip.Height);
  1378. TextFormatter?.Draw (ViewToScreen (Bounds), HasFocus ? ColorScheme.Focus : GetNormalColor (),
  1379. HasFocus ? ColorScheme.HotFocus : Enabled ? ColorScheme.HotNormal : ColorScheme.Disabled,
  1380. containerBounds);
  1381. }
  1382. // Invoke DrawContentEvent
  1383. OnDrawContent (bounds);
  1384. if (subviews != null) {
  1385. foreach (var view in subviews) {
  1386. if (!view.NeedDisplay.IsEmpty || view.ChildNeedsDisplay || view.LayoutNeeded) {
  1387. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1388. if (view.LayoutNeeded)
  1389. view.LayoutSubviews ();
  1390. // Draw the subview
  1391. // Use the view's bounds (view-relative; Location will always be (0,0)
  1392. if (view.Visible && view.Frame.Width > 0 && view.Frame.Height > 0) {
  1393. var rect = new Rect () {
  1394. X = Math.Min (view.Bounds.X, view.NeedDisplay.X),
  1395. Y = Math.Min (view.Bounds.Y, view.NeedDisplay.Y),
  1396. Width = Math.Max (view.Bounds.Width, view.NeedDisplay.Width),
  1397. Height = Math.Max (view.Bounds.Height, view.NeedDisplay.Height)
  1398. };
  1399. view.OnDrawContent (rect);
  1400. view.Redraw (rect);
  1401. }
  1402. }
  1403. view.NeedDisplay = Rect.Empty;
  1404. view.ChildNeedsDisplay = false;
  1405. }
  1406. }
  1407. }
  1408. // Invoke DrawContentCompleteEvent
  1409. OnDrawContentComplete (bounds);
  1410. ClearLayoutNeeded ();
  1411. ClearNeedsDisplay ();
  1412. }
  1413. /// <summary>
  1414. /// Event invoked when the content area of the View is to be drawn.
  1415. /// </summary>
  1416. /// <remarks>
  1417. /// <para>
  1418. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1419. /// </para>
  1420. /// <para>
  1421. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1422. /// </para>
  1423. /// </remarks>
  1424. public event Action<Rect> DrawContent;
  1425. /// <summary>
  1426. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1427. /// </summary>
  1428. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1429. /// <remarks>
  1430. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1431. /// </remarks>
  1432. public virtual void OnDrawContent (Rect viewport)
  1433. {
  1434. DrawContent?.Invoke (viewport);
  1435. }
  1436. /// <summary>
  1437. /// Event invoked when the content area of the View is completed drawing.
  1438. /// </summary>
  1439. /// <remarks>
  1440. /// <para>
  1441. /// Will be invoked after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1442. /// </para>
  1443. /// <para>
  1444. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1445. /// </para>
  1446. /// </remarks>
  1447. public event Action<Rect> DrawContentComplete;
  1448. /// <summary>
  1449. /// Enables overrides after completed drawing infinitely scrolled content and/or a background behind removed controls.
  1450. /// </summary>
  1451. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1452. /// <remarks>
  1453. /// This method will be called after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1454. /// </remarks>
  1455. public virtual void OnDrawContentComplete (Rect viewport)
  1456. {
  1457. DrawContentComplete?.Invoke (viewport);
  1458. }
  1459. /// <summary>
  1460. /// Causes the specified subview to have focus.
  1461. /// </summary>
  1462. /// <param name="view">View.</param>
  1463. void SetFocus (View view)
  1464. {
  1465. if (view == null)
  1466. return;
  1467. //Console.WriteLine ($"Request to focus {view}");
  1468. if (!view.CanFocus || !view.Visible || !view.Enabled)
  1469. return;
  1470. if (focused?.hasFocus == true && focused == view)
  1471. return;
  1472. // Make sure that this view is a subview
  1473. View c;
  1474. for (c = view.container; c != null; c = c.container)
  1475. if (c == this)
  1476. break;
  1477. if (c == null)
  1478. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1479. if (focused != null)
  1480. focused.SetHasFocus (false, view);
  1481. var f = focused;
  1482. focused = view;
  1483. focused.SetHasFocus (true, f);
  1484. focused.EnsureFocus ();
  1485. // Send focus upwards
  1486. SuperView?.SetFocus (this);
  1487. }
  1488. /// <summary>
  1489. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  1490. /// </summary>
  1491. public void SetFocus ()
  1492. {
  1493. if (!CanBeVisible (this) || !Enabled) {
  1494. if (HasFocus) {
  1495. SetHasFocus (false, this);
  1496. }
  1497. return;
  1498. }
  1499. SuperView?.SetFocus (this);
  1500. }
  1501. /// <summary>
  1502. /// Defines the event arguments for <see cref="KeyEvent"/>
  1503. /// </summary>
  1504. public class KeyEventEventArgs : EventArgs {
  1505. /// <summary>
  1506. /// Constructs.
  1507. /// </summary>
  1508. /// <param name="ke"></param>
  1509. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  1510. /// <summary>
  1511. /// The <see cref="KeyEvent"/> for the event.
  1512. /// </summary>
  1513. public KeyEvent KeyEvent { get; set; }
  1514. /// <summary>
  1515. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1516. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1517. /// </summary>
  1518. public bool Handled { get; set; } = false;
  1519. }
  1520. /// <summary>
  1521. /// Invoked when a character key is pressed and occurs after the key up event.
  1522. /// </summary>
  1523. public event Action<KeyEventEventArgs> KeyPress;
  1524. /// <inheritdoc/>
  1525. public override bool ProcessKey (KeyEvent keyEvent)
  1526. {
  1527. if (!Enabled) {
  1528. return false;
  1529. }
  1530. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1531. KeyPress?.Invoke (args);
  1532. if (args.Handled)
  1533. return true;
  1534. if (Focused?.Enabled == true) {
  1535. Focused?.KeyPress?.Invoke (args);
  1536. if (args.Handled)
  1537. return true;
  1538. }
  1539. if (Focused?.Enabled == true && Focused?.ProcessKey (keyEvent) == true)
  1540. return true;
  1541. return false;
  1542. }
  1543. /// <summary>
  1544. /// Invokes any binding that is registered on this <see cref="View"/>
  1545. /// and matches the <paramref name="keyEvent"/>
  1546. /// </summary>
  1547. /// <param name="keyEvent">The key event passed.</param>
  1548. protected bool? InvokeKeybindings (KeyEvent keyEvent)
  1549. {
  1550. if (KeyBindings.ContainsKey (keyEvent.Key)) {
  1551. var command = KeyBindings [keyEvent.Key];
  1552. if (!CommandImplementations.ContainsKey (command)) {
  1553. throw new NotSupportedException ($"A KeyBinding was set up for the command {command} ({keyEvent.Key}) but that command is not supported by this View ({GetType ().Name})");
  1554. }
  1555. return CommandImplementations [command] ();
  1556. }
  1557. return null;
  1558. }
  1559. /// <summary>
  1560. /// <para>Adds a new key combination that will trigger the given <paramref name="command"/>
  1561. /// (if supported by the View - see <see cref="GetSupportedCommands"/>)
  1562. /// </para>
  1563. /// <para>If the key is already bound to a different <see cref="Command"/> it will be
  1564. /// rebound to this one</para>
  1565. /// </summary>
  1566. /// <param name="key"></param>
  1567. /// <param name="command"></param>
  1568. public void AddKeyBinding (Key key, Command command)
  1569. {
  1570. if (KeyBindings.ContainsKey (key)) {
  1571. KeyBindings [key] = command;
  1572. } else {
  1573. KeyBindings.Add (key, command);
  1574. }
  1575. }
  1576. /// <summary>
  1577. /// Replaces a key combination already bound to <see cref="Command"/>.
  1578. /// </summary>
  1579. /// <param name="fromKey">The key to be replaced.</param>
  1580. /// <param name="toKey">The new key to be used.</param>
  1581. protected void ReplaceKeyBinding (Key fromKey, Key toKey)
  1582. {
  1583. if (KeyBindings.ContainsKey (fromKey)) {
  1584. Command value = KeyBindings [fromKey];
  1585. KeyBindings.Remove (fromKey);
  1586. KeyBindings [toKey] = value;
  1587. }
  1588. }
  1589. /// <summary>
  1590. /// Checks if key combination already exist.
  1591. /// </summary>
  1592. /// <param name="key">The key to check.</param>
  1593. /// <returns><c>true</c> If the key already exist, <c>false</c>otherwise.</returns>
  1594. public bool ContainsKeyBinding (Key key)
  1595. {
  1596. return KeyBindings.ContainsKey (key);
  1597. }
  1598. /// <summary>
  1599. /// Removes all bound keys from the View making including the default
  1600. /// key combinations such as cursor navigation, scrolling etc
  1601. /// </summary>
  1602. public void ClearKeybindings ()
  1603. {
  1604. KeyBindings.Clear ();
  1605. }
  1606. /// <summary>
  1607. /// Clears the existing keybinding (if any) for the given <paramref name="key"/>
  1608. /// </summary>
  1609. /// <param name="key"></param>
  1610. public void ClearKeybinding (Key key)
  1611. {
  1612. KeyBindings.Remove (key);
  1613. }
  1614. /// <summary>
  1615. /// Removes all key bindings that trigger the given command. Views can have multiple different
  1616. /// keys bound to the same command and this method will clear all of them.
  1617. /// </summary>
  1618. /// <param name="command"></param>
  1619. public void ClearKeybinding (Command command)
  1620. {
  1621. foreach (var kvp in KeyBindings.Where (kvp => kvp.Value == command).ToArray ()) {
  1622. KeyBindings.Remove (kvp.Key);
  1623. }
  1624. }
  1625. /// <summary>
  1626. /// <para>States that the given <see cref="View"/> supports a given <paramref name="command"/>
  1627. /// and what <paramref name="f"/> to perform to make that command happen
  1628. /// </para>
  1629. /// <para>If the <paramref name="command"/> already has an implementation the <paramref name="f"/>
  1630. /// will replace the old one</para>
  1631. /// </summary>
  1632. /// <param name="command">The command.</param>
  1633. /// <param name="f">The function.</param>
  1634. protected void AddCommand (Command command, Func<bool?> f)
  1635. {
  1636. // if there is already an implementation of this command
  1637. if (CommandImplementations.ContainsKey (command)) {
  1638. // replace that implementation
  1639. CommandImplementations [command] = f;
  1640. } else {
  1641. // else record how to perform the action (this should be the normal case)
  1642. CommandImplementations.Add (command, f);
  1643. }
  1644. }
  1645. /// <summary>
  1646. /// Returns all commands that are supported by this <see cref="View"/>
  1647. /// </summary>
  1648. /// <returns></returns>
  1649. public IEnumerable<Command> GetSupportedCommands ()
  1650. {
  1651. return CommandImplementations.Keys;
  1652. }
  1653. /// <summary>
  1654. /// Gets the key used by a command.
  1655. /// </summary>
  1656. /// <param name="command">The command to search.</param>
  1657. /// <returns>The <see cref="Key"/> used by a <see cref="Command"/></returns>
  1658. public Key GetKeyFromCommand (Command command)
  1659. {
  1660. return KeyBindings.First (x => x.Value == command).Key;
  1661. }
  1662. /// <inheritdoc/>
  1663. public override bool ProcessHotKey (KeyEvent keyEvent)
  1664. {
  1665. if (!Enabled) {
  1666. return false;
  1667. }
  1668. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1669. if (MostFocused?.Enabled == true) {
  1670. MostFocused?.KeyPress?.Invoke (args);
  1671. if (args.Handled)
  1672. return true;
  1673. }
  1674. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1675. return true;
  1676. if (subviews == null || subviews.Count == 0)
  1677. return false;
  1678. foreach (var view in subviews)
  1679. if (view.Enabled && view.ProcessHotKey (keyEvent))
  1680. return true;
  1681. return false;
  1682. }
  1683. /// <inheritdoc/>
  1684. public override bool ProcessColdKey (KeyEvent keyEvent)
  1685. {
  1686. if (!Enabled) {
  1687. return false;
  1688. }
  1689. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1690. KeyPress?.Invoke (args);
  1691. if (args.Handled)
  1692. return true;
  1693. if (MostFocused?.Enabled == true) {
  1694. MostFocused?.KeyPress?.Invoke (args);
  1695. if (args.Handled)
  1696. return true;
  1697. }
  1698. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1699. return true;
  1700. if (subviews == null || subviews.Count == 0)
  1701. return false;
  1702. foreach (var view in subviews)
  1703. if (view.Enabled && view.ProcessColdKey (keyEvent))
  1704. return true;
  1705. return false;
  1706. }
  1707. /// <summary>
  1708. /// Invoked when a key is pressed
  1709. /// </summary>
  1710. public event Action<KeyEventEventArgs> KeyDown;
  1711. /// <inheritdoc/>
  1712. public override bool OnKeyDown (KeyEvent keyEvent)
  1713. {
  1714. if (!Enabled) {
  1715. return false;
  1716. }
  1717. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1718. KeyDown?.Invoke (args);
  1719. if (args.Handled) {
  1720. return true;
  1721. }
  1722. if (Focused?.Enabled == true && Focused?.OnKeyDown (keyEvent) == true) {
  1723. return true;
  1724. }
  1725. return false;
  1726. }
  1727. /// <summary>
  1728. /// Invoked when a key is released
  1729. /// </summary>
  1730. public event Action<KeyEventEventArgs> KeyUp;
  1731. /// <inheritdoc/>
  1732. public override bool OnKeyUp (KeyEvent keyEvent)
  1733. {
  1734. if (!Enabled) {
  1735. return false;
  1736. }
  1737. KeyEventEventArgs args = new KeyEventEventArgs (keyEvent);
  1738. KeyUp?.Invoke (args);
  1739. if (args.Handled) {
  1740. return true;
  1741. }
  1742. if (Focused?.Enabled == true && Focused?.OnKeyUp (keyEvent) == true) {
  1743. return true;
  1744. }
  1745. return false;
  1746. }
  1747. /// <summary>
  1748. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1749. /// </summary>
  1750. public void EnsureFocus ()
  1751. {
  1752. if (focused == null && subviews?.Count > 0) {
  1753. if (FocusDirection == Direction.Forward) {
  1754. FocusFirst ();
  1755. } else {
  1756. FocusLast ();
  1757. }
  1758. }
  1759. }
  1760. /// <summary>
  1761. /// Focuses the first focusable subview if one exists.
  1762. /// </summary>
  1763. public void FocusFirst ()
  1764. {
  1765. if (!CanBeVisible (this)) {
  1766. return;
  1767. }
  1768. if (tabIndexes == null) {
  1769. SuperView?.SetFocus (this);
  1770. return;
  1771. }
  1772. foreach (var view in tabIndexes) {
  1773. if (view.CanFocus && view.tabStop && view.Visible && view.Enabled) {
  1774. SetFocus (view);
  1775. return;
  1776. }
  1777. }
  1778. }
  1779. /// <summary>
  1780. /// Focuses the last focusable subview if one exists.
  1781. /// </summary>
  1782. public void FocusLast ()
  1783. {
  1784. if (!CanBeVisible (this)) {
  1785. return;
  1786. }
  1787. if (tabIndexes == null) {
  1788. SuperView?.SetFocus (this);
  1789. return;
  1790. }
  1791. for (int i = tabIndexes.Count; i > 0;) {
  1792. i--;
  1793. View v = tabIndexes [i];
  1794. if (v.CanFocus && v.tabStop && v.Visible && v.Enabled) {
  1795. SetFocus (v);
  1796. return;
  1797. }
  1798. }
  1799. }
  1800. /// <summary>
  1801. /// Focuses the previous view.
  1802. /// </summary>
  1803. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1804. public bool FocusPrev ()
  1805. {
  1806. if (!CanBeVisible (this)) {
  1807. return false;
  1808. }
  1809. FocusDirection = Direction.Backward;
  1810. if (tabIndexes == null || tabIndexes.Count == 0)
  1811. return false;
  1812. if (focused == null) {
  1813. FocusLast ();
  1814. return focused != null;
  1815. }
  1816. int focused_idx = -1;
  1817. for (int i = tabIndexes.Count; i > 0;) {
  1818. i--;
  1819. View w = tabIndexes [i];
  1820. if (w.HasFocus) {
  1821. if (w.FocusPrev ())
  1822. return true;
  1823. focused_idx = i;
  1824. continue;
  1825. }
  1826. if (w.CanFocus && focused_idx != -1 && w.tabStop && w.Visible && w.Enabled) {
  1827. focused.SetHasFocus (false, w);
  1828. if (w != null && w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  1829. w.FocusLast ();
  1830. SetFocus (w);
  1831. return true;
  1832. }
  1833. }
  1834. if (focused != null) {
  1835. focused.SetHasFocus (false, this);
  1836. focused = null;
  1837. }
  1838. return false;
  1839. }
  1840. /// <summary>
  1841. /// Focuses the next view.
  1842. /// </summary>
  1843. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1844. public bool FocusNext ()
  1845. {
  1846. if (!CanBeVisible (this)) {
  1847. return false;
  1848. }
  1849. FocusDirection = Direction.Forward;
  1850. if (tabIndexes == null || tabIndexes.Count == 0)
  1851. return false;
  1852. if (focused == null) {
  1853. FocusFirst ();
  1854. return focused != null;
  1855. }
  1856. int n = tabIndexes.Count;
  1857. int focused_idx = -1;
  1858. for (int i = 0; i < n; i++) {
  1859. View w = tabIndexes [i];
  1860. if (w.HasFocus) {
  1861. if (w.FocusNext ())
  1862. return true;
  1863. focused_idx = i;
  1864. continue;
  1865. }
  1866. if (w.CanFocus && focused_idx != -1 && w.tabStop && w.Visible && w.Enabled) {
  1867. focused.SetHasFocus (false, w);
  1868. if (w != null && w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  1869. w.FocusFirst ();
  1870. SetFocus (w);
  1871. return true;
  1872. }
  1873. }
  1874. if (focused != null) {
  1875. focused.SetHasFocus (false, this);
  1876. focused = null;
  1877. }
  1878. return false;
  1879. }
  1880. View GetMostFocused (View view)
  1881. {
  1882. if (view == null) {
  1883. return view;
  1884. }
  1885. if (view.focused != null) {
  1886. return GetMostFocused (view.focused);
  1887. } else {
  1888. return view;
  1889. }
  1890. }
  1891. /// <summary>
  1892. /// Sets the View's <see cref="Frame"/> to the relative coordinates if its container, given the <see cref="Frame"/> for its container.
  1893. /// </summary>
  1894. /// <param name="hostFrame">The screen-relative frame for the host.</param>
  1895. /// <remarks>
  1896. /// Reminder: <see cref="Frame"/> is superview-relative; <see cref="Bounds"/> is view-relative.
  1897. /// </remarks>
  1898. internal void SetRelativeLayout (Rect hostFrame)
  1899. {
  1900. int w, h, _x, _y;
  1901. var s = Size.Empty;
  1902. if (AutoSize) {
  1903. s = CalculateAutoSize ();
  1904. }
  1905. if (x is Pos.PosCenter) {
  1906. if (width == null) {
  1907. w = AutoSize ? s.Width : hostFrame.Width;
  1908. } else {
  1909. w = width.Anchor (hostFrame.Width);
  1910. w = AutoSize && s.Width > w ? s.Width : w;
  1911. }
  1912. _x = x.Anchor (hostFrame.Width - w);
  1913. } else {
  1914. if (x == null)
  1915. _x = 0;
  1916. else
  1917. _x = x.Anchor (hostFrame.Width);
  1918. if (width == null) {
  1919. w = AutoSize ? s.Width : hostFrame.Width;
  1920. } else if (width is Dim.DimFactor && !((Dim.DimFactor)width).IsFromRemaining ()) {
  1921. w = width.Anchor (hostFrame.Width);
  1922. w = AutoSize && s.Width > w ? s.Width : w;
  1923. } else {
  1924. w = Math.Max (width.Anchor (hostFrame.Width - _x), 0);
  1925. w = AutoSize && s.Width > w ? s.Width : w;
  1926. }
  1927. }
  1928. if (y is Pos.PosCenter) {
  1929. if (height == null) {
  1930. h = AutoSize ? s.Height : hostFrame.Height;
  1931. } else {
  1932. h = height.Anchor (hostFrame.Height);
  1933. h = AutoSize && s.Height > h ? s.Height : h;
  1934. }
  1935. _y = y.Anchor (hostFrame.Height - h);
  1936. } else {
  1937. if (y == null)
  1938. _y = 0;
  1939. else
  1940. _y = y.Anchor (hostFrame.Height);
  1941. if (height == null) {
  1942. h = AutoSize ? s.Height : hostFrame.Height;
  1943. } else if (height is Dim.DimFactor && !((Dim.DimFactor)height).IsFromRemaining ()) {
  1944. h = height.Anchor (hostFrame.Height);
  1945. h = AutoSize && s.Height > h ? s.Height : h;
  1946. } else {
  1947. h = Math.Max (height.Anchor (hostFrame.Height - _y), 0);
  1948. h = AutoSize && s.Height > h ? s.Height : h;
  1949. }
  1950. }
  1951. var r = new Rect (_x, _y, w, h);
  1952. if (Frame != r) {
  1953. Frame = new Rect (_x, _y, w, h);
  1954. if (!SetMinWidthHeight ())
  1955. TextFormatter.Size = GetBoundsTextFormatterSize ();
  1956. }
  1957. }
  1958. // https://en.wikipedia.org/wiki/Topological_sorting
  1959. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1960. {
  1961. var result = new List<View> ();
  1962. // Set of all nodes with no incoming edges
  1963. var S = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  1964. while (S.Any ()) {
  1965. // remove a node n from S
  1966. var n = S.First ();
  1967. S.Remove (n);
  1968. // add n to tail of L
  1969. if (n != this?.SuperView)
  1970. result.Add (n);
  1971. // for each node m with an edge e from n to m do
  1972. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1973. var m = e.To;
  1974. // remove edge e from the graph
  1975. edges.Remove (e);
  1976. // if m has no other incoming edges then
  1977. if (edges.All (me => !me.To.Equals (m)) && m != this?.SuperView) {
  1978. // insert m into S
  1979. S.Add (m);
  1980. }
  1981. }
  1982. }
  1983. if (edges.Any ()) {
  1984. var (from, to) = edges.First ();
  1985. if (from != Application.Top) {
  1986. if (!ReferenceEquals (from, to)) {
  1987. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {from} linked with {to}. Did you forget to add it to {this}?");
  1988. } else {
  1989. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + this);
  1990. }
  1991. }
  1992. }
  1993. // return L (a topologically sorted order)
  1994. return result;
  1995. }
  1996. /// <summary>
  1997. /// Event arguments for the <see cref="LayoutComplete"/> event.
  1998. /// </summary>
  1999. public class LayoutEventArgs : EventArgs {
  2000. /// <summary>
  2001. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  2002. /// </summary>
  2003. public Rect OldBounds { get; set; }
  2004. }
  2005. /// <summary>
  2006. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  2007. /// </summary>
  2008. /// <remarks>
  2009. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2010. /// </remarks>
  2011. public event Action<LayoutEventArgs> LayoutStarted;
  2012. /// <summary>
  2013. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  2014. /// </summary>
  2015. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  2016. {
  2017. LayoutStarted?.Invoke (args);
  2018. }
  2019. /// <summary>
  2020. /// Fired after the Views's <see cref="LayoutSubviews"/> method has completed.
  2021. /// </summary>
  2022. /// <remarks>
  2023. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2024. /// </remarks>
  2025. public event Action<LayoutEventArgs> LayoutComplete;
  2026. /// <summary>
  2027. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  2028. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  2029. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  2030. /// </summary>
  2031. public event EventHandler Initialized;
  2032. /// <summary>
  2033. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  2034. /// </summary>
  2035. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  2036. {
  2037. LayoutComplete?.Invoke (args);
  2038. }
  2039. /// <summary>
  2040. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  2041. /// response to the container view or terminal resizing.
  2042. /// </summary>
  2043. /// <remarks>
  2044. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  2045. /// </remarks>
  2046. public virtual void LayoutSubviews ()
  2047. {
  2048. if (!LayoutNeeded) {
  2049. return;
  2050. }
  2051. Rect oldBounds = Bounds;
  2052. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  2053. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2054. // Sort out the dependencies of the X, Y, Width, Height properties
  2055. var nodes = new HashSet<View> ();
  2056. var edges = new HashSet<(View, View)> ();
  2057. void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2058. {
  2059. if (pos is Pos.PosView pv) {
  2060. if (pv.Target != this) {
  2061. nEdges.Add ((pv.Target, from));
  2062. }
  2063. foreach (var v in from.InternalSubviews) {
  2064. CollectAll (v, ref nNodes, ref nEdges);
  2065. }
  2066. return;
  2067. }
  2068. if (pos is Pos.PosCombine pc) {
  2069. foreach (var v in from.InternalSubviews) {
  2070. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  2071. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  2072. }
  2073. }
  2074. }
  2075. void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2076. {
  2077. if (dim is Dim.DimView dv) {
  2078. if (dv.Target != this) {
  2079. nEdges.Add ((dv.Target, from));
  2080. }
  2081. foreach (var v in from.InternalSubviews) {
  2082. CollectAll (v, ref nNodes, ref nEdges);
  2083. }
  2084. return;
  2085. }
  2086. if (dim is Dim.DimCombine dc) {
  2087. foreach (var v in from.InternalSubviews) {
  2088. CollectDim (dc.left, from, ref nNodes, ref nEdges);
  2089. CollectDim (dc.right, from, ref nNodes, ref nEdges);
  2090. }
  2091. }
  2092. }
  2093. void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2094. {
  2095. foreach (var v in from.InternalSubviews) {
  2096. nNodes.Add (v);
  2097. if (v.layoutStyle != LayoutStyle.Computed) {
  2098. continue;
  2099. }
  2100. CollectPos (v.X, v, ref nNodes, ref nEdges);
  2101. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  2102. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  2103. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  2104. }
  2105. }
  2106. CollectAll (this, ref nodes, ref edges);
  2107. var ordered = TopologicalSort (nodes, edges);
  2108. foreach (var v in ordered) {
  2109. if (v.LayoutStyle == LayoutStyle.Computed) {
  2110. v.SetRelativeLayout (Frame);
  2111. }
  2112. v.LayoutSubviews ();
  2113. v.LayoutNeeded = false;
  2114. }
  2115. if (SuperView != null && SuperView == Application.Top && LayoutNeeded
  2116. && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  2117. SetRelativeLayout (SuperView.Frame);
  2118. }
  2119. LayoutNeeded = false;
  2120. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  2121. }
  2122. ustring text;
  2123. /// <summary>
  2124. /// The text displayed by the <see cref="View"/>.
  2125. /// </summary>
  2126. /// <remarks>
  2127. /// <para>
  2128. /// If provided, the text will be drawn before any subviews are drawn.
  2129. /// </para>
  2130. /// <para>
  2131. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  2132. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  2133. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  2134. /// is 1, the text will be clipped.
  2135. /// </para>
  2136. /// <para>
  2137. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  2138. /// <c>(Rune)0xffff</c>.
  2139. /// </para>
  2140. /// </remarks>
  2141. public virtual ustring Text {
  2142. get => text;
  2143. set {
  2144. text = value;
  2145. SetHotKey ();
  2146. UpdateTextFormatterText ();
  2147. ProcessResizeView ();
  2148. }
  2149. }
  2150. /// <summary>
  2151. /// Used by <see cref="Text"/> to resize the view's <see cref="Bounds"/> with the <see cref="TextFormatter.Size"/>.
  2152. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="Width"/> and <see cref="Height"/> are null or
  2153. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout
  2154. /// and <see cref="ForceValidatePosDim"/> to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  2155. /// </summary>
  2156. public virtual bool AutoSize {
  2157. get => autoSize;
  2158. set {
  2159. var v = ResizeView (value);
  2160. TextFormatter.AutoSize = v;
  2161. if (autoSize != v) {
  2162. autoSize = v;
  2163. TextFormatter.NeedsFormat = true;
  2164. UpdateTextFormatterText ();
  2165. ProcessResizeView ();
  2166. }
  2167. }
  2168. }
  2169. /// <summary>
  2170. /// Get or sets a flag if the wrapped text will keep the trailing spaces or
  2171. /// the trailing spaces will be trimmed (default).
  2172. /// </summary>
  2173. public virtual bool PreserveTrailingSpaces {
  2174. get => TextFormatter.PreserveTrailingSpaces;
  2175. set {
  2176. if (TextFormatter.PreserveTrailingSpaces != value) {
  2177. TextFormatter.PreserveTrailingSpaces = value;
  2178. TextFormatter.NeedsFormat = true;
  2179. }
  2180. }
  2181. }
  2182. /// <summary>
  2183. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  2184. /// </summary>
  2185. /// <value>The text alignment.</value>
  2186. public virtual TextAlignment TextAlignment {
  2187. get => TextFormatter.Alignment;
  2188. set {
  2189. TextFormatter.Alignment = value;
  2190. UpdateTextFormatterText ();
  2191. ProcessResizeView ();
  2192. }
  2193. }
  2194. /// <summary>
  2195. /// Gets or sets how the View's <see cref="Text"/> is aligned verticaly when drawn. Changing this property will redisplay the <see cref="View"/>.
  2196. /// </summary>
  2197. /// <value>The text alignment.</value>
  2198. public virtual VerticalTextAlignment VerticalTextAlignment {
  2199. get => TextFormatter.VerticalAlignment;
  2200. set {
  2201. TextFormatter.VerticalAlignment = value;
  2202. SetNeedsDisplay ();
  2203. }
  2204. }
  2205. /// <summary>
  2206. /// Gets or sets the direction of the View's <see cref="Text"/>. Changing this property will redisplay the <see cref="View"/>.
  2207. /// </summary>
  2208. /// <value>The text alignment.</value>
  2209. public virtual TextDirection TextDirection {
  2210. get => TextFormatter.Direction;
  2211. set {
  2212. if (TextFormatter.Direction != value) {
  2213. var isValidOldAutSize = autoSize && IsValidAutoSize (out Size autSize);
  2214. var directionChanged = TextFormatter.IsHorizontalDirection (TextFormatter.Direction)
  2215. != TextFormatter.IsHorizontalDirection (value);
  2216. TextFormatter.Direction = value;
  2217. UpdateTextFormatterText ();
  2218. if ((!ForceValidatePosDim && directionChanged && AutoSize)
  2219. || (ForceValidatePosDim && directionChanged && AutoSize && isValidOldAutSize)) {
  2220. ProcessResizeView ();
  2221. } else if (directionChanged && IsAdded) {
  2222. SetWidthHeight (Bounds.Size);
  2223. SetMinWidthHeight ();
  2224. } else {
  2225. SetMinWidthHeight ();
  2226. }
  2227. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2228. SetNeedsDisplay ();
  2229. }
  2230. }
  2231. }
  2232. /// <summary>
  2233. /// Get or sets if the <see cref="View"/> was already initialized.
  2234. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  2235. /// </summary>
  2236. public virtual bool IsInitialized { get; set; }
  2237. /// <summary>
  2238. /// Gets information if the view was already added to the superview.
  2239. /// </summary>
  2240. public bool IsAdded { get; private set; }
  2241. bool oldEnabled;
  2242. /// <inheritdoc/>
  2243. public override bool Enabled {
  2244. get => base.Enabled;
  2245. set {
  2246. if (base.Enabled != value) {
  2247. base.Enabled = value;
  2248. if (!value && HasFocus) {
  2249. SetHasFocus (false, this);
  2250. }
  2251. OnEnabledChanged ();
  2252. SetNeedsDisplay ();
  2253. if (subviews != null) {
  2254. foreach (var view in subviews) {
  2255. if (!value) {
  2256. view.oldEnabled = view.Enabled;
  2257. view.Enabled = value;
  2258. } else {
  2259. view.Enabled = view.oldEnabled;
  2260. view.addingView = false;
  2261. }
  2262. }
  2263. }
  2264. }
  2265. }
  2266. }
  2267. /// <inheritdoc/>>
  2268. public override bool Visible {
  2269. get => base.Visible;
  2270. set {
  2271. if (base.Visible != value) {
  2272. base.Visible = value;
  2273. if (!value && HasFocus) {
  2274. SetHasFocus (false, this);
  2275. }
  2276. OnVisibleChanged ();
  2277. SetNeedsDisplay ();
  2278. }
  2279. }
  2280. }
  2281. Border border;
  2282. /// <inheritdoc/>
  2283. public virtual Border Border {
  2284. get => border;
  2285. set {
  2286. if (border != value) {
  2287. border = value;
  2288. SetNeedsDisplay ();
  2289. }
  2290. }
  2291. }
  2292. /// <summary>
  2293. /// Pretty prints the View
  2294. /// </summary>
  2295. /// <returns></returns>
  2296. public override string ToString ()
  2297. {
  2298. return $"{GetType ().Name}({Id})({Frame})";
  2299. }
  2300. void SetHotKey ()
  2301. {
  2302. TextFormatter.FindHotKey (text, HotKeySpecifier, true, out _, out Key hk);
  2303. if (hotKey != hk) {
  2304. HotKey = hk;
  2305. }
  2306. }
  2307. bool ResizeView (bool autoSize)
  2308. {
  2309. if (!autoSize) {
  2310. return false;
  2311. }
  2312. var aSize = true;
  2313. var nBoundsSize = CalculateAutoSize ();
  2314. if (nBoundsSize != Bounds.Size) {
  2315. if (ForceValidatePosDim) {
  2316. aSize = SetWidthHeight (nBoundsSize);
  2317. } else {
  2318. Bounds = new Rect (Bounds.X, Bounds.Y, nBoundsSize.Width, nBoundsSize.Height);
  2319. }
  2320. }
  2321. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2322. return aSize;
  2323. }
  2324. bool SetWidthHeight (Size nBounds)
  2325. {
  2326. bool aSize = false;
  2327. var canSizeW = SetWidth (nBounds.Width - GetHotKeySpecifierLength (), out int rW);
  2328. var canSizeH = SetHeight (nBounds.Height - GetHotKeySpecifierLength (false), out int rH);
  2329. if (canSizeW) {
  2330. aSize = true;
  2331. width = rW;
  2332. }
  2333. if (canSizeH) {
  2334. aSize = true;
  2335. height = rH;
  2336. }
  2337. if (aSize) {
  2338. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  2339. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2340. }
  2341. return aSize;
  2342. }
  2343. /// <summary>
  2344. /// Calculates the size to fit all text if <see cref="AutoSize"/> is true.
  2345. /// </summary>
  2346. /// <returns>The <see cref="Size"/></returns>
  2347. public Size CalculateAutoSize ()
  2348. {
  2349. var rect = TextFormatter.CalcRect (Bounds.X, Bounds.Y, TextFormatter.Text, TextFormatter.Direction);
  2350. return new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2351. rect.Size.Height - GetHotKeySpecifierLength (false));
  2352. }
  2353. /// <summary>
  2354. /// Calculates the width to fit the text if <see cref="AutoSize"/> is true.
  2355. /// </summary>
  2356. /// <returns>The width length.</returns>
  2357. public int CalculateAutoSizeWidth ()
  2358. {
  2359. return CalculateAutoSize ().Width;
  2360. }
  2361. /// <summary>
  2362. /// Calculates the height to fit the text if <see cref="AutoSize"/> is true.
  2363. /// </summary>
  2364. /// <returns>The height length.</returns>
  2365. public int CalculateAutoSizeHeight ()
  2366. {
  2367. return CalculateAutoSize ().Height;
  2368. }
  2369. bool IsValidAutoSize (out Size autoSize)
  2370. {
  2371. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2372. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2373. rect.Size.Height - GetHotKeySpecifierLength (false));
  2374. return !(ForceValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  2375. || frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  2376. || frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  2377. }
  2378. bool IsValidAutoSizeWidth (Dim width)
  2379. {
  2380. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2381. var dimValue = width.Anchor (0);
  2382. return !(ForceValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
  2383. - GetHotKeySpecifierLength ());
  2384. }
  2385. bool IsValidAutoSizeHeight (Dim height)
  2386. {
  2387. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2388. var dimValue = height.Anchor (0);
  2389. return !(ForceValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
  2390. - GetHotKeySpecifierLength (false));
  2391. }
  2392. /// <summary>
  2393. /// Get the width or height of the <see cref="TextFormatter.HotKeySpecifier"/> length.
  2394. /// </summary>
  2395. /// <param name="isWidth"><c>true</c>if is the width (default)<c>false</c>if is the height.</param>
  2396. /// <returns>The length of the <see cref="TextFormatter.HotKeySpecifier"/>.</returns>
  2397. public int GetHotKeySpecifierLength (bool isWidth = true)
  2398. {
  2399. if (isWidth) {
  2400. return TextFormatter.IsHorizontalDirection (TextDirection) &&
  2401. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2402. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2403. } else {
  2404. return TextFormatter.IsVerticalDirection (TextDirection) &&
  2405. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2406. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2407. }
  2408. }
  2409. /// <summary>
  2410. /// Gets the bounds size from a <see cref="TextFormatter.Size"/>.
  2411. /// </summary>
  2412. /// <returns>The bounds size minus the <see cref="TextFormatter.HotKeySpecifier"/> length.</returns>
  2413. public Size GetTextFormatterBoundsSize ()
  2414. {
  2415. return new Size (TextFormatter.Size.Width - GetHotKeySpecifierLength (),
  2416. TextFormatter.Size.Height - GetHotKeySpecifierLength (false));
  2417. }
  2418. /// <summary>
  2419. /// Gets the text formatter size from a <see cref="Bounds"/> size.
  2420. /// </summary>
  2421. /// <returns>The text formatter size more the <see cref="TextFormatter.HotKeySpecifier"/> length.</returns>
  2422. public Size GetBoundsTextFormatterSize ()
  2423. {
  2424. if (TextFormatter.Text == null)
  2425. return Bounds.Size;
  2426. return new Size (frame.Size.Width + GetHotKeySpecifierLength (),
  2427. frame.Size.Height + GetHotKeySpecifierLength (false));
  2428. }
  2429. /// <summary>
  2430. /// Specifies the event arguments for <see cref="MouseEvent"/>
  2431. /// </summary>
  2432. public class MouseEventArgs : EventArgs {
  2433. /// <summary>
  2434. /// Constructs.
  2435. /// </summary>
  2436. /// <param name="me"></param>
  2437. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  2438. /// <summary>
  2439. /// The <see cref="MouseEvent"/> for the event.
  2440. /// </summary>
  2441. public MouseEvent MouseEvent { get; set; }
  2442. /// <summary>
  2443. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  2444. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  2445. /// </summary>
  2446. public bool Handled { get; set; }
  2447. }
  2448. /// <inheritdoc/>
  2449. public override bool OnMouseEnter (MouseEvent mouseEvent)
  2450. {
  2451. if (!Enabled) {
  2452. return true;
  2453. }
  2454. if (!CanBeVisible (this)) {
  2455. return false;
  2456. }
  2457. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  2458. MouseEnter?.Invoke (args);
  2459. if (args.Handled)
  2460. return true;
  2461. if (base.OnMouseEnter (mouseEvent))
  2462. return true;
  2463. return false;
  2464. }
  2465. /// <inheritdoc/>
  2466. public override bool OnMouseLeave (MouseEvent mouseEvent)
  2467. {
  2468. if (!Enabled) {
  2469. return true;
  2470. }
  2471. if (!CanBeVisible (this)) {
  2472. return false;
  2473. }
  2474. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  2475. MouseLeave?.Invoke (args);
  2476. if (args.Handled)
  2477. return true;
  2478. if (base.OnMouseLeave (mouseEvent))
  2479. return true;
  2480. return false;
  2481. }
  2482. /// <summary>
  2483. /// Method invoked when a mouse event is generated
  2484. /// </summary>
  2485. /// <param name="mouseEvent"></param>
  2486. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  2487. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  2488. {
  2489. if (!Enabled) {
  2490. return true;
  2491. }
  2492. if (!CanBeVisible (this)) {
  2493. return false;
  2494. }
  2495. MouseEventArgs args = new MouseEventArgs (mouseEvent);
  2496. if (OnMouseClick (args))
  2497. return true;
  2498. if (MouseEvent (mouseEvent))
  2499. return true;
  2500. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  2501. if (CanFocus && !HasFocus && SuperView != null) {
  2502. SuperView.SetFocus (this);
  2503. SetNeedsDisplay ();
  2504. }
  2505. return true;
  2506. }
  2507. return false;
  2508. }
  2509. /// <summary>
  2510. /// Invokes the MouseClick event.
  2511. /// </summary>
  2512. protected bool OnMouseClick (MouseEventArgs args)
  2513. {
  2514. if (!Enabled) {
  2515. return true;
  2516. }
  2517. MouseClick?.Invoke (args);
  2518. return args.Handled;
  2519. }
  2520. /// <inheritdoc/>
  2521. public override void OnCanFocusChanged () => CanFocusChanged?.Invoke ();
  2522. /// <inheritdoc/>
  2523. public override void OnEnabledChanged () => EnabledChanged?.Invoke ();
  2524. /// <inheritdoc/>
  2525. public override void OnVisibleChanged () => VisibleChanged?.Invoke ();
  2526. /// <inheritdoc/>
  2527. protected override void Dispose (bool disposing)
  2528. {
  2529. for (int i = InternalSubviews.Count - 1; i >= 0; i--) {
  2530. View subview = InternalSubviews [i];
  2531. Remove (subview);
  2532. subview.Dispose ();
  2533. }
  2534. base.Dispose (disposing);
  2535. }
  2536. /// <summary>
  2537. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are beginning initialized.
  2538. /// </summary>
  2539. public void BeginInit ()
  2540. {
  2541. if (!IsInitialized) {
  2542. oldCanFocus = CanFocus;
  2543. oldTabIndex = tabIndex;
  2544. }
  2545. if (subviews?.Count > 0) {
  2546. foreach (var view in subviews) {
  2547. if (!view.IsInitialized) {
  2548. view.BeginInit ();
  2549. }
  2550. }
  2551. }
  2552. }
  2553. /// <summary>
  2554. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are ending initialized.
  2555. /// </summary>
  2556. public void EndInit ()
  2557. {
  2558. IsInitialized = true;
  2559. if (subviews?.Count > 0) {
  2560. foreach (var view in subviews) {
  2561. if (!view.IsInitialized) {
  2562. view.EndInit ();
  2563. }
  2564. }
  2565. }
  2566. Initialized?.Invoke (this, EventArgs.Empty);
  2567. }
  2568. bool CanBeVisible (View view)
  2569. {
  2570. if (!view.Visible) {
  2571. return false;
  2572. }
  2573. for (var c = view.SuperView; c != null; c = c.SuperView) {
  2574. if (!c.Visible) {
  2575. return false;
  2576. }
  2577. }
  2578. return true;
  2579. }
  2580. bool CanSetWidth (int desiredWidth, out int resultWidth)
  2581. {
  2582. int w = desiredWidth;
  2583. bool canSetWidth;
  2584. if (Width is Dim.DimCombine || Width is Dim.DimView || Width is Dim.DimFill) {
  2585. // It's a Dim.DimCombine and so can't be assigned. Let it have it's width anchored.
  2586. w = Width.Anchor (w);
  2587. canSetWidth = !ForceValidatePosDim;
  2588. } else if (Width is Dim.DimFactor factor) {
  2589. // Tries to get the SuperView width otherwise the view width.
  2590. var sw = SuperView != null ? SuperView.Frame.Width : w;
  2591. if (factor.IsFromRemaining ()) {
  2592. sw -= Frame.X;
  2593. }
  2594. w = Width.Anchor (sw);
  2595. canSetWidth = !ForceValidatePosDim;
  2596. } else {
  2597. canSetWidth = true;
  2598. }
  2599. resultWidth = w;
  2600. return canSetWidth;
  2601. }
  2602. bool CanSetHeight (int desiredHeight, out int resultHeight)
  2603. {
  2604. int h = desiredHeight;
  2605. bool canSetHeight;
  2606. if (Height is Dim.DimCombine || Height is Dim.DimView || Height is Dim.DimFill) {
  2607. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  2608. h = Height.Anchor (h);
  2609. canSetHeight = !ForceValidatePosDim;
  2610. } else if (Height is Dim.DimFactor factor) {
  2611. // Tries to get the SuperView height otherwise the view height.
  2612. var sh = SuperView != null ? SuperView.Frame.Height : h;
  2613. if (factor.IsFromRemaining ()) {
  2614. sh -= Frame.Y;
  2615. }
  2616. h = Height.Anchor (sh);
  2617. canSetHeight = !ForceValidatePosDim;
  2618. } else {
  2619. canSetHeight = true;
  2620. }
  2621. resultHeight = h;
  2622. return canSetHeight;
  2623. }
  2624. /// <summary>
  2625. /// Calculate the width based on the <see cref="Width"/> settings.
  2626. /// </summary>
  2627. /// <param name="desiredWidth">The desired width.</param>
  2628. /// <param name="resultWidth">The real result width.</param>
  2629. /// <returns><c>true</c> if the width can be directly assigned, <c>false</c> otherwise.</returns>
  2630. public bool SetWidth (int desiredWidth, out int resultWidth)
  2631. {
  2632. return CanSetWidth (desiredWidth, out resultWidth);
  2633. }
  2634. /// <summary>
  2635. /// Calculate the height based on the <see cref="Height"/> settings.
  2636. /// </summary>
  2637. /// <param name="desiredHeight">The desired height.</param>
  2638. /// <param name="resultHeight">The real result height.</param>
  2639. /// <returns><c>true</c> if the height can be directly assigned, <c>false</c> otherwise.</returns>
  2640. public bool SetHeight (int desiredHeight, out int resultHeight)
  2641. {
  2642. return CanSetHeight (desiredHeight, out resultHeight);
  2643. }
  2644. /// <summary>
  2645. /// Gets the current width based on the <see cref="Width"/> settings.
  2646. /// </summary>
  2647. /// <param name="currentWidth">The real current width.</param>
  2648. /// <returns><c>true</c> if the width can be directly assigned, <c>false</c> otherwise.</returns>
  2649. public bool GetCurrentWidth (out int currentWidth)
  2650. {
  2651. SetRelativeLayout (SuperView == null ? frame : SuperView.frame);
  2652. currentWidth = frame.Width;
  2653. return CanSetWidth (0, out _);
  2654. }
  2655. /// <summary>
  2656. /// Calculate the height based on the <see cref="Height"/> settings.
  2657. /// </summary>
  2658. /// <param name="currentHeight">The real current height.</param>
  2659. /// <returns><c>true</c> if the height can be directly assigned, <c>false</c> otherwise.</returns>
  2660. public bool GetCurrentHeight (out int currentHeight)
  2661. {
  2662. SetRelativeLayout (SuperView == null ? frame : SuperView.frame);
  2663. currentHeight = frame.Height;
  2664. return CanSetHeight (0, out _);
  2665. }
  2666. /// <summary>
  2667. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  2668. /// </summary>
  2669. /// <returns><see cref="ColorScheme.Normal"/> if <see cref="Enabled"/> is <see langword="true"/>
  2670. /// or <see cref="ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/></returns>
  2671. public Attribute GetNormalColor ()
  2672. {
  2673. return Enabled ? ColorScheme.Normal : ColorScheme.Disabled;
  2674. }
  2675. /// <summary>
  2676. /// Get the top superview of a given <see cref="View"/>.
  2677. /// </summary>
  2678. /// <returns>The superview view.</returns>
  2679. public View GetTopSuperView ()
  2680. {
  2681. View top = Application.Top;
  2682. for (var v = this?.SuperView; v != null; v = v.SuperView) {
  2683. if (v != null) {
  2684. top = v;
  2685. }
  2686. }
  2687. return top;
  2688. }
  2689. }
  2690. }