View.cs 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Reflection;
  7. using NStack;
  8. namespace Terminal.Gui {
  9. /// <summary>
  10. /// Determines the LayoutStyle for a <see cref="View"/>, if Absolute, during <see cref="View.LayoutSubviews"/>, the
  11. /// value from the <see cref="View.Frame"/> will be used, if the value is Computed, then <see cref="View.Frame"/>
  12. /// will be updated from the X, Y <see cref="Pos"/> objects and the Width and Height <see cref="Dim"/> objects.
  13. /// </summary>
  14. public enum LayoutStyle {
  15. /// <summary>
  16. /// The position and size of the view are based <see cref="View.Frame"/>.
  17. /// </summary>
  18. Absolute,
  19. /// <summary>
  20. /// The position and size of the view will be computed based on
  21. /// <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and <see cref="View.Height"/>. <see cref="View.Frame"/> will
  22. /// provide the absolute computed values.
  23. /// </summary>
  24. Computed
  25. }
  26. /// <summary>
  27. /// View is the base class for all views on the screen and represents a visible element that can render itself and
  28. /// contains zero or more nested views, called SubViews.
  29. /// </summary>
  30. /// <remarks>
  31. /// <para>
  32. /// The View defines the base functionality for user interface elements in Terminal.Gui. Views
  33. /// can contain one or more subviews, can respond to user input and render themselves on the screen.
  34. /// </para>
  35. /// <para>
  36. /// Views supports two layout styles: <see cref="LayoutStyle.Absolute"/> or <see cref="LayoutStyle.Computed"/>.
  37. /// The choice as to which layout style is used by the View
  38. /// is determined when the View is initialized. To create a View using Absolute layout, call a constructor that takes a
  39. /// Rect parameter to specify the absolute position and size (the View.<see cref="View.Frame "/>). To create a View
  40. /// using Computed layout use a constructor that does not take a Rect parameter and set the X, Y, Width and Height
  41. /// properties on the view. Both approaches use coordinates that are relative to the container they are being added to.
  42. /// </para>
  43. /// <para>
  44. /// To switch between Absolute and Computed layout, use the <see cref="LayoutStyle"/> property.
  45. /// </para>
  46. /// <para>
  47. /// Computed layout is more flexible and supports dynamic console apps where controls adjust layout
  48. /// as the terminal resizes or other Views change size or position. The X, Y, Width and Height
  49. /// properties are Dim and Pos objects that dynamically update the position of a view.
  50. /// The X and Y properties are of type <see cref="Pos"/>
  51. /// and you can use either absolute positions, percentages or anchor
  52. /// points. The Width and Height properties are of type
  53. /// <see cref="Dim"/> and can use absolute position,
  54. /// percentages and anchors. These are useful as they will take
  55. /// care of repositioning views when view's frames are resized or
  56. /// if the terminal size changes.
  57. /// </para>
  58. /// <para>
  59. /// Absolute layout requires specifying coordinates and sizes of Views explicitly, and the
  60. /// View will typically stay in a fixed position and size. To change the position and size use the
  61. /// <see cref="Frame"/> property.
  62. /// </para>
  63. /// <para>
  64. /// Subviews (child views) can be added to a View by calling the <see cref="Add(View)"/> method.
  65. /// The container of a View can be accessed with the <see cref="SuperView"/> property.
  66. /// </para>
  67. /// <para>
  68. /// To flag a region of the View's <see cref="Bounds"/> to be redrawn call <see cref="SetNeedsDisplay(Rect)"/>.
  69. /// To flag the entire view for redraw call <see cref="SetNeedsDisplay()"/>.
  70. /// </para>
  71. /// <para>
  72. /// Views have a <see cref="ColorScheme"/> property that defines the default colors that subviews
  73. /// should use for rendering. This ensures that the views fit in the context where
  74. /// they are being used, and allows for themes to be plugged in. For example, the
  75. /// default colors for windows and toplevels uses a blue background, while it uses
  76. /// a white background for dialog boxes and a red background for errors.
  77. /// </para>
  78. /// <para>
  79. /// Subclasses should not rely on <see cref="ColorScheme"/> being
  80. /// set at construction time. If a <see cref="ColorScheme"/> is not set on a view, the view will inherit the
  81. /// value from its <see cref="SuperView"/> and the value might only be valid once a view has been
  82. /// added to a SuperView.
  83. /// </para>
  84. /// <para>
  85. /// By using <see cref="ColorScheme"/> applications will work both
  86. /// in color as well as black and white displays.
  87. /// </para>
  88. /// <para>
  89. /// Views that are focusable should implement the <see cref="PositionCursor"/> to make sure that
  90. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  91. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  92. /// the last focused view. So views should make sure that they place the cursor
  93. /// in a visually sensible place.
  94. /// </para>
  95. /// <para>
  96. /// The <see cref="LayoutSubviews"/> method is invoked when the size or layout of a view has
  97. /// changed. The default processing system will keep the size and dimensions
  98. /// for views that use the <see cref="LayoutStyle.Absolute"/>, and will recompute the
  99. /// frames for the vies that use <see cref="LayoutStyle.Computed"/>.
  100. /// </para>
  101. /// <para>
  102. /// Views can also opt-in to more sophisticated initialization
  103. /// by implementing overrides to <see cref="ISupportInitialize.BeginInit"/> and
  104. /// <see cref="ISupportInitialize.EndInit"/> which will be called
  105. /// when the view is added to a <see cref="SuperView"/>.
  106. /// </para>
  107. /// <para>
  108. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification"/>
  109. /// can be implemented, in which case the <see cref="ISupportInitialize"/>
  110. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  111. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  112. /// to override base class layout code optimally by doing so only on first run,
  113. /// instead of on every run.
  114. /// </para>
  115. /// </remarks>
  116. public partial class View : Responder, ISupportInitializeNotification {
  117. internal enum Direction {
  118. Forward,
  119. Backward
  120. }
  121. // container == SuperView
  122. View _superView = null;
  123. View focused = null;
  124. Direction focusDirection;
  125. bool autoSize;
  126. ShortcutHelper shortcutHelper;
  127. /// <summary>
  128. /// Event fired when this view is added to another.
  129. /// </summary>
  130. public event EventHandler<SuperViewChangedEventArgs> Added;
  131. /// <summary>
  132. /// Event fired when this view is removed from another.
  133. /// </summary>
  134. public event EventHandler<SuperViewChangedEventArgs> Removed;
  135. /// <summary>
  136. /// Event fired when the view gets focus.
  137. /// </summary>
  138. public event EventHandler<FocusEventArgs> Enter;
  139. /// <summary>
  140. /// Event fired when the view looses focus.
  141. /// </summary>
  142. public event EventHandler<FocusEventArgs> Leave;
  143. /// <summary>
  144. /// Event fired when the view receives the mouse event for the first time.
  145. /// </summary>
  146. public event EventHandler<MouseEventEventArgs> MouseEnter;
  147. /// <summary>
  148. /// Event fired when the view receives a mouse event for the last time.
  149. /// </summary>
  150. public event EventHandler<MouseEventEventArgs> MouseLeave;
  151. /// <summary>
  152. /// Event fired when a mouse event is generated.
  153. /// </summary>
  154. public event EventHandler<MouseEventEventArgs> MouseClick;
  155. /// <summary>
  156. /// Event fired when the <see cref="CanFocus"/> value is being changed.
  157. /// </summary>
  158. public event EventHandler CanFocusChanged;
  159. /// <summary>
  160. /// Event fired when the <see cref="Enabled"/> value is being changed.
  161. /// </summary>
  162. public event EventHandler EnabledChanged;
  163. /// <summary>
  164. /// Event fired when the <see cref="Visible"/> value is being changed.
  165. /// </summary>
  166. public event EventHandler VisibleChanged;
  167. /// <summary>
  168. /// Event invoked when the <see cref="HotKey"/> is changed.
  169. /// </summary>
  170. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  171. Key hotKey = Key.Null;
  172. /// <summary>
  173. /// 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.
  174. /// </summary>
  175. public virtual Key HotKey {
  176. get => hotKey;
  177. set {
  178. if (hotKey != value) {
  179. hotKey = TextFormatter.HotKey = (value == Key.Unknown ? Key.Null : value);
  180. }
  181. }
  182. }
  183. /// <summary>
  184. /// 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'.
  185. /// </summary>
  186. public virtual Rune HotKeySpecifier {
  187. get {
  188. if (TextFormatter != null) {
  189. return TextFormatter.HotKeySpecifier;
  190. } else {
  191. return new Rune ('\xFFFF');
  192. }
  193. }
  194. set {
  195. TextFormatter.HotKeySpecifier = value;
  196. SetHotKey ();
  197. }
  198. }
  199. /// <summary>
  200. /// This is the global setting that can be used as a global shortcut to invoke an action if provided.
  201. /// </summary>
  202. public Key Shortcut {
  203. get => shortcutHelper.Shortcut;
  204. set {
  205. if (shortcutHelper.Shortcut != value && (ShortcutHelper.PostShortcutValidation (value) || value == Key.Null)) {
  206. shortcutHelper.Shortcut = value;
  207. }
  208. }
  209. }
  210. /// <summary>
  211. /// The keystroke combination used in the <see cref="Shortcut"/> as string.
  212. /// </summary>
  213. public ustring ShortcutTag => ShortcutHelper.GetShortcutTag (shortcutHelper.Shortcut);
  214. /// <summary>
  215. /// The action to run if the <see cref="Shortcut"/> is defined.
  216. /// </summary>
  217. public virtual Action ShortcutAction { get; set; }
  218. /// <summary>
  219. /// Gets or sets arbitrary data for the view.
  220. /// </summary>
  221. /// <remarks>This property is not used internally.</remarks>
  222. public object Data { get; set; }
  223. internal Direction FocusDirection {
  224. get => SuperView?.FocusDirection ?? focusDirection;
  225. set {
  226. if (SuperView != null)
  227. SuperView.FocusDirection = value;
  228. else
  229. focusDirection = value;
  230. }
  231. }
  232. /// <summary>
  233. /// Points to the current driver in use by the view, it is a convenience property
  234. /// for simplifying the development of new views.
  235. /// </summary>
  236. public static ConsoleDriver Driver => Application.Driver;
  237. static readonly IList<View> empty = new List<View> (0).AsReadOnly ();
  238. // This is null, and allocated on demand.
  239. List<View> subviews;
  240. /// <summary>
  241. /// This returns a list of the subviews contained by this view.
  242. /// </summary>
  243. /// <value>The subviews.</value>
  244. public IList<View> Subviews => subviews?.AsReadOnly () ?? empty;
  245. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  246. // to make the same mistakes our users make when they poke at the Subviews.
  247. internal IList<View> InternalSubviews => subviews ?? empty;
  248. // This is null, and allocated on demand.
  249. List<View> tabIndexes;
  250. /// <summary>
  251. /// Configurable keybindings supported by the control
  252. /// </summary>
  253. private Dictionary<Key, Command []> KeyBindings { get; set; } = new Dictionary<Key, Command []> ();
  254. private Dictionary<Command, Func<bool?>> CommandImplementations { get; set; } = new Dictionary<Command, Func<bool?>> ();
  255. /// <summary>
  256. /// This returns a tab index list of the subviews contained by this view.
  257. /// </summary>
  258. /// <value>The tabIndexes.</value>
  259. public IList<View> TabIndexes => tabIndexes?.AsReadOnly () ?? empty;
  260. int tabIndex = -1;
  261. /// <summary>
  262. /// Indicates the index of the current <see cref="View"/> from the <see cref="TabIndexes"/> list.
  263. /// </summary>
  264. public int TabIndex {
  265. get { return tabIndex; }
  266. set {
  267. if (!CanFocus) {
  268. tabIndex = -1;
  269. return;
  270. } else if (SuperView?.tabIndexes == null || SuperView?.tabIndexes.Count == 1) {
  271. tabIndex = 0;
  272. return;
  273. } else if (tabIndex == value) {
  274. return;
  275. }
  276. tabIndex = value > SuperView.tabIndexes.Count - 1 ? SuperView.tabIndexes.Count - 1 : value < 0 ? 0 : value;
  277. tabIndex = GetTabIndex (tabIndex);
  278. if (SuperView.tabIndexes.IndexOf (this) != tabIndex) {
  279. SuperView.tabIndexes.Remove (this);
  280. SuperView.tabIndexes.Insert (tabIndex, this);
  281. SetTabIndex ();
  282. }
  283. }
  284. }
  285. int GetTabIndex (int idx)
  286. {
  287. var i = 0;
  288. foreach (var v in SuperView.tabIndexes) {
  289. if (v.tabIndex == -1 || v == this) {
  290. continue;
  291. }
  292. i++;
  293. }
  294. return Math.Min (i, idx);
  295. }
  296. void SetTabIndex ()
  297. {
  298. var i = 0;
  299. foreach (var v in SuperView.tabIndexes) {
  300. if (v.tabIndex == -1) {
  301. continue;
  302. }
  303. v.tabIndex = i;
  304. i++;
  305. }
  306. }
  307. bool tabStop = true;
  308. /// <summary>
  309. /// This only be <see langword="true"/> if the <see cref="CanFocus"/> is also <see langword="true"/>
  310. /// and the focus can be avoided by setting this to <see langword="false"/>
  311. /// </summary>
  312. public bool TabStop {
  313. get => tabStop;
  314. set {
  315. if (tabStop == value) {
  316. return;
  317. }
  318. tabStop = CanFocus && value;
  319. }
  320. }
  321. bool oldCanFocus;
  322. int oldTabIndex;
  323. /// <inheritdoc/>
  324. public override bool CanFocus {
  325. get => base.CanFocus;
  326. set {
  327. if (!addingView && IsInitialized && SuperView?.CanFocus == false && value) {
  328. throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
  329. }
  330. if (base.CanFocus != value) {
  331. base.CanFocus = value;
  332. switch (value) {
  333. case false when tabIndex > -1:
  334. TabIndex = -1;
  335. break;
  336. case true when SuperView?.CanFocus == false && addingView:
  337. SuperView.CanFocus = true;
  338. break;
  339. }
  340. if (value && tabIndex == -1) {
  341. TabIndex = SuperView != null ? SuperView.tabIndexes.IndexOf (this) : -1;
  342. }
  343. TabStop = value;
  344. if (!value && SuperView?.Focused == this) {
  345. SuperView.focused = null;
  346. }
  347. if (!value && HasFocus) {
  348. SetHasFocus (false, this);
  349. SuperView?.EnsureFocus ();
  350. if (SuperView != null && SuperView.Focused == null) {
  351. SuperView.FocusNext ();
  352. if (SuperView.Focused == null) {
  353. Application.Current.FocusNext ();
  354. }
  355. Application.EnsuresTopOnFront ();
  356. }
  357. }
  358. if (subviews != null && IsInitialized) {
  359. foreach (var view in subviews) {
  360. if (view.CanFocus != value) {
  361. if (!value) {
  362. view.oldCanFocus = view.CanFocus;
  363. view.oldTabIndex = view.tabIndex;
  364. view.CanFocus = false;
  365. view.tabIndex = -1;
  366. } else {
  367. if (addingView) {
  368. view.addingView = true;
  369. }
  370. view.CanFocus = view.oldCanFocus;
  371. view.tabIndex = view.oldTabIndex;
  372. view.addingView = false;
  373. }
  374. }
  375. }
  376. }
  377. OnCanFocusChanged ();
  378. SetNeedsDisplay ();
  379. }
  380. }
  381. }
  382. // The frame for the object. Superview relative.
  383. Rect frame;
  384. /// <summary>
  385. /// Gets or sets an identifier for the view;
  386. /// </summary>
  387. /// <value>The identifier.</value>
  388. /// <remarks>The id should be unique across all Views that share a SuperView.</remarks>
  389. public string Id { get; set; } = "";
  390. /// <summary>
  391. /// Returns a value indicating if this View is currently on Top (Active)
  392. /// </summary>
  393. public bool IsCurrentTop => Application.Current == this;
  394. /// <summary>
  395. /// Gets or sets a value indicating whether this <see cref="View"/> wants mouse position reports.
  396. /// </summary>
  397. /// <value><see langword="true"/> if want mouse position reports; otherwise, <see langword="false"/>.</value>
  398. public virtual bool WantMousePositionReports { get; set; }
  399. /// <summary>
  400. /// Gets or sets a value indicating whether this <see cref="View"/> want continuous button pressed event.
  401. /// </summary>
  402. public virtual bool WantContinuousButtonPressed { get; set; }
  403. /// <summary>
  404. /// Gets or sets the frame for the view. The frame is relative to the view's container (<see cref="SuperView"/>).
  405. /// </summary>
  406. /// <value>The frame.</value>
  407. /// <remarks>
  408. /// <para>
  409. /// Change the Frame when using the <see cref="Terminal.Gui.LayoutStyle.Absolute"/> layout style to move or resize views.
  410. /// </para>
  411. /// <para>
  412. /// Altering the Frame of a view will trigger the redrawing of the
  413. /// view as well as the redrawing of the affected regions of the <see cref="SuperView"/>.
  414. /// </para>
  415. /// </remarks>
  416. public virtual Rect Frame {
  417. get => frame;
  418. set {
  419. frame = new Rect (value.X, value.Y, Math.Max (value.Width, 0), Math.Max (value.Height, 0));
  420. if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
  421. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  422. LayoutFrames ();
  423. SetNeedsLayout ();
  424. SetNeedsDisplay ();
  425. }
  426. }
  427. }
  428. /// <summary>
  429. /// The Thickness that separates a View from other SubViews of the same SuperView.
  430. /// The Margin is not part of the View's content and is not clipped by the View's Clip Area.
  431. /// </summary>
  432. public Frame Margin { get; private set; }
  433. // TODO: Rename BorderFrame to Border
  434. /// <summary>
  435. /// Thickness where a visual border (drawn using line-drawing glyphs) and the Title are drawn.
  436. /// The Border expands inward; in other words if `Border.Thickness.Top == 2` the border and
  437. /// title will take up the first row and the second row will be filled with spaces.
  438. /// The Border is not part of the View's content and is not clipped by the View's `ClipArea`.
  439. /// </summary>
  440. public Frame BorderFrame { get; private set; }
  441. /// <summary>
  442. /// Means the Thickness inside of an element that offsets the `Content` from the Border.
  443. /// Padding is `{0, 0, 0, 0}` by default. Padding is not part of the View's content and is not clipped by the View's `ClipArea`.
  444. /// </summary>
  445. /// <remarks>
  446. /// (NOTE: in v1 `Padding` is OUTSIDE of the `Border`).
  447. /// </remarks>
  448. public Frame Padding { get; private set; }
  449. /// <summary>
  450. /// Helper to get the X and Y offset of the Bounds from the Frame. This is the sum of the Left and Top properties of
  451. /// <see cref="Margin"/>, <see cref="BorderFrame"/> and <see cref="Padding"/>.
  452. /// </summary>
  453. public Point GetBoundsOffset () => new Point (Padding?.Thickness.GetInside (Padding.Frame).X ?? 0, Padding?.Thickness.GetInside (Padding.Frame).Y ?? 0);
  454. /// <summary>
  455. /// Creates the view's <see cref="Frame"/> objects. This internal method is overridden by Frame to do nothing
  456. /// to prevent recursion during View construction.
  457. /// </summary>
  458. internal virtual void CreateFrames ()
  459. {
  460. void ThicknessChangedHandler (object sender, EventArgs e)
  461. {
  462. SetNeedsLayout ();
  463. }
  464. if (Margin != null) {
  465. Margin.ThicknessChanged -= ThicknessChangedHandler;
  466. Margin.Dispose ();
  467. }
  468. Margin = new Frame () { Id = "Margin", Thickness = new Thickness (0) };
  469. Margin.ThicknessChanged += ThicknessChangedHandler;
  470. Margin.Parent = this;
  471. if (BorderFrame != null) {
  472. BorderFrame.ThicknessChanged -= ThicknessChangedHandler;
  473. BorderFrame.Dispose ();
  474. }
  475. // TODO: create default for borderstyle
  476. BorderFrame = new Frame () { Id = "BorderFrame", Thickness = new Thickness (0), BorderStyle = BorderStyle.Single };
  477. BorderFrame.ThicknessChanged += ThicknessChangedHandler;
  478. BorderFrame.Parent = this;
  479. // TODO: Create View.AddAdornment
  480. if (Padding != null) {
  481. Padding.ThicknessChanged -= ThicknessChangedHandler;
  482. Padding.Dispose ();
  483. }
  484. Padding = new Frame () { Id = "Padding", Thickness = new Thickness (0) };
  485. Padding.ThicknessChanged += ThicknessChangedHandler;
  486. Padding.Parent = this;
  487. }
  488. ustring title = ustring.Empty;
  489. /// <summary>
  490. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="BorderFrame"/>.<see cref="Thickness.Top"/>
  491. /// is greater than 0.
  492. /// </summary>
  493. /// <value>The title.</value>
  494. public ustring Title {
  495. get => title;
  496. set {
  497. if (!OnTitleChanging (title, value)) {
  498. var old = title;
  499. title = value;
  500. SetNeedsDisplay ();
  501. #if DEBUG
  502. if (title != null && string.IsNullOrEmpty (Id)) {
  503. Id = title.ToString ();
  504. }
  505. #endif // DEBUG
  506. OnTitleChanged (old, title);
  507. }
  508. }
  509. }
  510. /// <summary>
  511. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can be cancelled.
  512. /// </summary>
  513. /// <param name="oldTitle">The <see cref="View.Title"/> that is/has been replaced.</param>
  514. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  515. /// <returns>`true` if an event handler canceled the Title change.</returns>
  516. public virtual bool OnTitleChanging (ustring oldTitle, ustring newTitle)
  517. {
  518. var args = new TitleEventArgs (oldTitle, newTitle);
  519. TitleChanging?.Invoke (this, args);
  520. return args.Cancel;
  521. }
  522. /// <summary>
  523. /// Event fired when the <see cref="View.Title"/> is changing. Set <see cref="TitleEventArgs.Cancel"/> to
  524. /// `true` to cancel the Title change.
  525. /// </summary>
  526. public event EventHandler<TitleEventArgs> TitleChanging;
  527. /// <summary>
  528. /// Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.
  529. /// </summary>
  530. /// <param name="oldTitle">The <see cref="View.Title"/> that is/has been replaced.</param>
  531. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  532. public virtual void OnTitleChanged (ustring oldTitle, ustring newTitle)
  533. {
  534. var args = new TitleEventArgs (oldTitle, newTitle);
  535. TitleChanged?.Invoke (this, args);
  536. }
  537. /// <summary>
  538. /// Event fired after the <see cref="View.Title"/> has been changed.
  539. /// </summary>
  540. public event EventHandler<TitleEventArgs> TitleChanged;
  541. LayoutStyle _layoutStyle;
  542. /// <summary>
  543. /// Controls how the View's <see cref="Frame"/> is computed during the LayoutSubviews method, if the style is set to
  544. /// <see cref="Terminal.Gui.LayoutStyle.Absolute"/>,
  545. /// LayoutSubviews does not change the <see cref="Frame"/>. If the style is <see cref="Terminal.Gui.LayoutStyle.Computed"/>
  546. /// the <see cref="Frame"/> is updated using
  547. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  548. /// </summary>
  549. /// <value>The layout style.</value>
  550. public LayoutStyle LayoutStyle {
  551. get => _layoutStyle;
  552. set {
  553. _layoutStyle = value;
  554. SetNeedsLayout ();
  555. }
  556. }
  557. /// <summary>
  558. /// The View-relative rectangle where View content is displayed. SubViews are positioned relative to
  559. /// Bounds.<see cref="Rect.Location">Location</see> (which is always (0, 0)) and <see cref="Redraw(Rect)"/> clips drawing to
  560. /// Bounds.<see cref="Rect.Size">Size</see>.
  561. /// </summary>
  562. /// <value>The bounds.</value>
  563. /// <remarks>
  564. /// <para>
  565. /// The <see cref="Rect.Location"/> of Bounds is always (0, 0). To obtain the offset of the Bounds from the Frame use
  566. /// <see cref="GetBoundsOffset"/>.
  567. /// </para>
  568. /// </remarks>
  569. public virtual Rect Bounds {
  570. get {
  571. #if DEBUG
  572. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized) {
  573. Debug.WriteLine ($"WARNING: Bounds is being accessed before the View has been initialized. This is likely a bug. View: {this}");
  574. }
  575. #endif // DEBUG
  576. var frameRelativeBounds = Padding?.Thickness.GetInside (Padding.Frame) ?? new Rect (default, Frame.Size);
  577. return new Rect (default, frameRelativeBounds.Size);
  578. }
  579. set {
  580. // BUGBUG: Margin etc.. can be null (if typeof(Frame))
  581. Frame = new Rect (Frame.Location,
  582. new Size (
  583. value.Size.Width + Margin.Thickness.Horizontal + BorderFrame.Thickness.Horizontal + Padding.Thickness.Horizontal,
  584. value.Size.Height + Margin.Thickness.Vertical + BorderFrame.Thickness.Vertical + Padding.Thickness.Vertical
  585. )
  586. );
  587. ;
  588. }
  589. }
  590. // Diagnostics to highlight when X or Y is read before the view has been initialized
  591. private Pos VerifyIsIntialized (Pos pos)
  592. {
  593. #if DEBUG
  594. if (LayoutStyle == LayoutStyle.Computed && (!IsInitialized)) {
  595. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; position is indeterminate {pos}. This is likely a bug.");
  596. }
  597. #endif // DEBUG
  598. return pos;
  599. }
  600. // Diagnostics to highlight when Width or Height is read before the view has been initialized
  601. private Dim VerifyIsIntialized (Dim dim)
  602. {
  603. #if DEBUG
  604. if (LayoutStyle == LayoutStyle.Computed && (!IsInitialized)) {
  605. Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; dimension is indeterminate: {dim}. This is likely a bug.");
  606. }
  607. #endif // DEBUG
  608. return dim;
  609. }
  610. Pos x, y;
  611. /// <summary>
  612. /// Gets or sets the X position for the view (the column). Only used if the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  613. /// </summary>
  614. /// <value>The X Position.</value>
  615. /// <remarks>
  616. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  617. /// </remarks>
  618. public Pos X {
  619. get => VerifyIsIntialized (x);
  620. set {
  621. if (ForceValidatePosDim && !ValidatePosDim (x, value)) {
  622. throw new ArgumentException ();
  623. }
  624. x = value;
  625. OnResizeNeeded ();
  626. }
  627. }
  628. /// <summary>
  629. /// Gets or sets the Y position for the view (the row). Only used if the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  630. /// </summary>
  631. /// <value>The y position (line).</value>
  632. /// <remarks>
  633. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  634. /// </remarks>
  635. public Pos Y {
  636. get => VerifyIsIntialized (y);
  637. set {
  638. if (ForceValidatePosDim && !ValidatePosDim (y, value)) {
  639. throw new ArgumentException ();
  640. }
  641. y = value;
  642. OnResizeNeeded ();
  643. }
  644. }
  645. Dim width, height;
  646. /// <summary>
  647. /// Gets or sets the width of the view. Only used the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  648. /// </summary>
  649. /// <value>The width.</value>
  650. /// <remarks>
  651. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  652. /// </remarks>
  653. public Dim Width {
  654. get => VerifyIsIntialized (width);
  655. set {
  656. if (ForceValidatePosDim && !ValidatePosDim (width, value)) {
  657. throw new ArgumentException ("ForceValidatePosDim is enabled", nameof (Width));
  658. }
  659. width = value;
  660. if (ForceValidatePosDim) {
  661. var isValidNewAutSize = autoSize && IsValidAutoSizeWidth (width);
  662. if (IsAdded && autoSize && !isValidNewAutSize) {
  663. throw new InvalidOperationException ("Must set AutoSize to false before set the Width.");
  664. }
  665. }
  666. OnResizeNeeded ();
  667. }
  668. }
  669. /// <summary>
  670. /// Gets or sets the height of the view. Only used the <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  671. /// </summary>
  672. /// <value>The height.</value>
  673. /// If <see cref="LayoutStyle"/> is <see cref="Terminal.Gui.LayoutStyle.Absolute"/> changing this property has no effect and its value is indeterminate.
  674. public Dim Height {
  675. get => VerifyIsIntialized (height);
  676. set {
  677. if (ForceValidatePosDim && !ValidatePosDim (height, value)) {
  678. throw new ArgumentException ("ForceValidatePosDim is enabled", nameof (Height));
  679. }
  680. height = value;
  681. if (ForceValidatePosDim) {
  682. var isValidNewAutSize = autoSize && IsValidAutoSizeHeight (height);
  683. if (IsAdded && autoSize && !isValidNewAutSize) {
  684. throw new InvalidOperationException ("Must set AutoSize to false before set the Height.");
  685. }
  686. }
  687. OnResizeNeeded ();
  688. }
  689. }
  690. /// <summary>
  691. /// Forces validation with <see cref="Terminal.Gui.LayoutStyle.Computed"/> layout
  692. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  693. /// </summary>
  694. public bool ForceValidatePosDim { get; set; }
  695. bool ValidatePosDim (object oldValue, object newValue)
  696. {
  697. if (!IsInitialized || _layoutStyle == LayoutStyle.Absolute || oldValue == null || oldValue.GetType () == newValue.GetType () || this is Toplevel) {
  698. return true;
  699. }
  700. if (_layoutStyle == LayoutStyle.Computed) {
  701. if (oldValue.GetType () != newValue.GetType () && !(newValue is Pos.PosAbsolute || newValue is Dim.DimAbsolute)) {
  702. return true;
  703. }
  704. }
  705. return false;
  706. }
  707. // BUGBUG: This API is broken - It should be renamed to `GetMinimumBoundsForFrame and
  708. // should not assume Frame.Height == Bounds.Height
  709. /// <summary>
  710. /// Gets the minimum dimensions required to fit the View's <see cref="Text"/>, factoring in <see cref="TextDirection"/>.
  711. /// </summary>
  712. /// <param name="size">The minimum dimensions required.</param>
  713. /// <returns><see langword="true"/> if the dimensions fit within the View's <see cref="Bounds"/>, <see langword="false"/> otherwise.</returns>
  714. /// <remarks>
  715. /// Always returns <see langword="false"/> if <see cref="AutoSize"/> is <see langword="true"/> or
  716. /// if <see cref="Height"/> (Horizontal) or <see cref="Width"/> (Vertical) are not not set or zero.
  717. /// Does not take into account word wrapping.
  718. /// </remarks>
  719. public bool GetMinimumBounds (out Size size)
  720. {
  721. size = Bounds.Size;
  722. if (!AutoSize && !ustring.IsNullOrEmpty (TextFormatter.Text)) {
  723. switch (TextFormatter.IsVerticalDirection (TextDirection)) {
  724. case true:
  725. var colWidth = TextFormatter.GetSumMaxCharWidth (new List<ustring> { TextFormatter.Text }, 0, 1);
  726. // TODO: v2 - This uses frame.Width; it should only use Bounds
  727. if (frame.Width < colWidth &&
  728. (Width == null ||
  729. (Bounds.Width >= 0 &&
  730. Width is Dim.DimAbsolute &&
  731. Width.Anchor (0) >= 0 &&
  732. Width.Anchor (0) < colWidth))) {
  733. size = new Size (colWidth, Bounds.Height);
  734. return true;
  735. }
  736. break;
  737. default:
  738. if (frame.Height < 1 &&
  739. (Height == null ||
  740. (Height is Dim.DimAbsolute &&
  741. Height.Anchor (0) == 0))) {
  742. size = new Size (Bounds.Width, 1);
  743. return true;
  744. }
  745. break;
  746. }
  747. }
  748. return false;
  749. }
  750. // BUGBUG - v2 - Should be renamed "SetBoundsToFitFrame"
  751. /// <summary>
  752. /// Sets the size of the View to the minimum width or height required to fit <see cref="Text"/> (see <see cref="GetMinimumBounds(out Size)"/>.
  753. /// </summary>
  754. /// <returns><see langword="true"/> if the size was changed, <see langword="false"/> if <see cref="Text"/>
  755. /// will not fit.</returns>
  756. public bool SetMinWidthHeight ()
  757. {
  758. if (IsInitialized && GetMinimumBounds (out Size size)) {
  759. Bounds = new Rect (Bounds.Location, size);
  760. return true;
  761. }
  762. return false;
  763. }
  764. /// <summary>
  765. /// Gets or sets the <see cref="Terminal.Gui.TextFormatter"/> which can be handled differently by any derived class.
  766. /// </summary>
  767. public TextFormatter? TextFormatter { get; set; }
  768. /// <summary>
  769. /// Returns the container for this view, or null if this view has not been added to a container.
  770. /// </summary>
  771. /// <value>The super view.</value>
  772. public virtual View SuperView {
  773. get {
  774. return _superView;
  775. }
  776. set {
  777. throw new NotImplementedException ();
  778. }
  779. }
  780. /// <summary>
  781. /// Initializes a new instance of a <see cref="Terminal.Gui.LayoutStyle.Absolute"/> <see cref="View"/> class with the absolute
  782. /// dimensions specified in the <see langword="frame"/> parameter.
  783. /// </summary>
  784. /// <param name="frame">The region covered by this view.</param>
  785. /// <remarks>
  786. /// This constructor initialize a View with a <see cref="LayoutStyle"/> of <see cref="Terminal.Gui.LayoutStyle.Absolute"/>.
  787. /// Use <see cref="View"/> to initialize a View with <see cref="LayoutStyle"/> of <see cref="Terminal.Gui.LayoutStyle.Computed"/>
  788. /// </remarks>
  789. public View (Rect frame) : this (frame, null, null) { }
  790. /// <summary>
  791. /// Initializes a new instance of <see cref="View"/> using <see cref="Terminal.Gui.LayoutStyle.Computed"/> layout.
  792. /// </summary>
  793. /// <remarks>
  794. /// <para>
  795. /// 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.
  796. /// The <see cref="View"/> will be created using <see cref="Terminal.Gui.LayoutStyle.Computed"/>
  797. /// coordinates. The initial size (<see cref="View.Frame"/>) will be
  798. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  799. /// </para>
  800. /// <para>
  801. /// If <see cref="Height"/> is greater than one, word wrapping is provided.
  802. /// </para>
  803. /// <para>
  804. /// This constructor initialize a View with a <see cref="LayoutStyle"/> of <see cref="Terminal.Gui.LayoutStyle.Computed"/>.
  805. /// 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.
  806. /// </para>
  807. /// </remarks>
  808. public View () : this (text: string.Empty, direction: TextDirection.LeftRight_TopBottom) { }
  809. /// <summary>
  810. /// Initializes a new instance of <see cref="View"/> using <see cref="Terminal.Gui.LayoutStyle.Absolute"/> layout.
  811. /// </summary>
  812. /// <remarks>
  813. /// <para>
  814. /// The <see cref="View"/> will be created at the given
  815. /// coordinates with the given string. The size (<see cref="View.Frame"/>) will be
  816. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  817. /// </para>
  818. /// <para>
  819. /// No line wrapping is provided.
  820. /// </para>
  821. /// </remarks>
  822. /// <param name="x">column to locate the View.</param>
  823. /// <param name="y">row to locate the View.</param>
  824. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  825. public View (int x, int y, ustring text) : this (TextFormatter.CalcRect (x, y, text), text) { }
  826. /// <summary>
  827. /// Initializes a new instance of <see cref="View"/> using <see cref="Terminal.Gui.LayoutStyle.Absolute"/> layout.
  828. /// </summary>
  829. /// <remarks>
  830. /// <para>
  831. /// The <see cref="View"/> will be created at the given
  832. /// coordinates with the given string. The initial size (<see cref="View.Frame"/>) will be
  833. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  834. /// </para>
  835. /// <para>
  836. /// If <c>rect.Height</c> is greater than one, word wrapping is provided.
  837. /// </para>
  838. /// </remarks>
  839. /// <param name="rect">Location.</param>
  840. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  841. /// <param name="border">The <see cref="Border"/>.</param>
  842. public View (Rect rect, ustring text, Border border = null)
  843. {
  844. SetInitialProperties (text, rect, LayoutStyle.Absolute, TextDirection.LeftRight_TopBottom, border);
  845. }
  846. /// <summary>
  847. /// Initializes a new instance of <see cref="View"/> using <see cref="Terminal.Gui.LayoutStyle.Computed"/> layout.
  848. /// </summary>
  849. /// <remarks>
  850. /// <para>
  851. /// The <see cref="View"/> will be created using <see cref="Terminal.Gui.LayoutStyle.Computed"/>
  852. /// coordinates with the given string. The initial size (<see cref="View.Frame"/>) will be
  853. /// adjusted to fit the contents of <see cref="Text"/>, including newlines ('\n') for multiple lines.
  854. /// </para>
  855. /// <para>
  856. /// If <see cref="Height"/> is greater than one, word wrapping is provided.
  857. /// </para>
  858. /// </remarks>
  859. /// <param name="text">text to initialize the <see cref="Text"/> property with.</param>
  860. /// <param name="direction">The text direction.</param>
  861. /// <param name="border">The <see cref="Border"/>.</param>
  862. public View (ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom, Border border = null)
  863. {
  864. SetInitialProperties (text, Rect.Empty, LayoutStyle.Computed, direction, border);
  865. }
  866. // TODO: v2 - Remove constructors with parameters
  867. /// <summary>
  868. /// Private helper to set the initial properties of the View that were provided via constructors.
  869. /// </summary>
  870. /// <param name="text"></param>
  871. /// <param name="rect"></param>
  872. /// <param name="layoutStyle"></param>
  873. /// <param name="direction"></param>
  874. /// <param name="border"></param>
  875. void SetInitialProperties (ustring text, Rect rect, LayoutStyle layoutStyle = LayoutStyle.Computed,
  876. TextDirection direction = TextDirection.LeftRight_TopBottom, Border border = null)
  877. {
  878. TextFormatter = new TextFormatter ();
  879. TextFormatter.HotKeyChanged += TextFormatter_HotKeyChanged;
  880. TextDirection = direction;
  881. shortcutHelper = new ShortcutHelper ();
  882. CanFocus = false;
  883. TabIndex = -1;
  884. TabStop = false;
  885. LayoutStyle = layoutStyle;
  886. Border = border;
  887. Text = text == null ? ustring.Empty : text;
  888. LayoutStyle = layoutStyle;
  889. var r = rect.IsEmpty ? TextFormatter.CalcRect (0, 0, text, direction) : rect;
  890. Frame = r;
  891. OnResizeNeeded ();
  892. CreateFrames ();
  893. LayoutFrames ();
  894. }
  895. // TODO: v2 - Hack for now
  896. private void Border_BorderChanged (Border border)
  897. {
  898. //if (!border.DrawMarginFrame) BorderFrame.BorderStyle = BorderStyle.None;
  899. BorderFrame.BorderStyle = border.BorderStyle;
  900. BorderFrame.Thickness = new Thickness (BorderFrame.BorderStyle == BorderStyle.None ? 0 : 1);
  901. }
  902. /// <summary>
  903. /// Can be overridden if the <see cref="Terminal.Gui.TextFormatter.Text"/> has
  904. /// different format than the default.
  905. /// </summary>
  906. protected virtual void UpdateTextFormatterText ()
  907. {
  908. if (TextFormatter != null) {
  909. TextFormatter.Text = text;
  910. }
  911. }
  912. /// <summary>
  913. /// Called whenever the view needs to be resized.
  914. /// Can be overridden if the view resize behavior is
  915. /// different than the default.
  916. /// </summary>
  917. protected virtual void OnResizeNeeded ()
  918. {
  919. var actX = x is Pos.PosAbsolute ? x.Anchor (0) : frame.X;
  920. var actY = y is Pos.PosAbsolute ? y.Anchor (0) : frame.Y;
  921. if (AutoSize) {
  922. var s = GetAutoSize ();
  923. var w = width is Dim.DimAbsolute && width.Anchor (0) > s.Width ? width.Anchor (0) : s.Width;
  924. var h = height is Dim.DimAbsolute && height.Anchor (0) > s.Height ? height.Anchor (0) : s.Height;
  925. Frame = new Rect (new Point (actX, actY), new Size (w, h));
  926. } else {
  927. var w = width is Dim.DimAbsolute ? width.Anchor (0) : frame.Width;
  928. var h = height is Dim.DimAbsolute ? height.Anchor (0) : frame.Height;
  929. // BUGBUG: v2 - ? - If layoutstyle is absolute, this overwrites the current frame h/w with 0. Hmmm...
  930. Frame = new Rect (new Point (actX, actY), new Size (w, h));
  931. SetMinWidthHeight ();
  932. }
  933. //// BUGBUG: I think these calls are redundant or should be moved into just the AutoSize case
  934. //TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  935. SetNeedsLayout ();
  936. //SetNeedsDisplay ();
  937. }
  938. void TextFormatter_HotKeyChanged (object sender, KeyChangedEventArgs e)
  939. {
  940. HotKeyChanged?.Invoke (this, e);
  941. }
  942. internal bool LayoutNeeded { get; private set; } = true;
  943. internal void SetNeedsLayout ()
  944. {
  945. if (LayoutNeeded)
  946. return;
  947. LayoutNeeded = true;
  948. if (SuperView == null)
  949. return;
  950. SuperView.SetNeedsLayout ();
  951. foreach (var view in Subviews) {
  952. view.SetNeedsLayout ();
  953. }
  954. TextFormatter.NeedsFormat = true;
  955. }
  956. /// <summary>
  957. /// Removes the <see cref="SetNeedsLayout"/> setting on this view.
  958. /// </summary>
  959. protected void ClearLayoutNeeded ()
  960. {
  961. LayoutNeeded = false;
  962. }
  963. // The view-relative region that needs to be redrawn
  964. internal Rect _needsDisplay { get; private set; } = Rect.Empty;
  965. /// <summary>
  966. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  967. /// </summary>
  968. public void SetNeedsDisplay ()
  969. {
  970. if (!IsInitialized) return;
  971. SetNeedsDisplay (Bounds);
  972. }
  973. /// <summary>
  974. /// Flags the view-relative region on this View as needing to be redrawn.
  975. /// </summary>
  976. /// <param name="region">The view-relative region that needs to be redrawn.</param>
  977. public void SetNeedsDisplay (Rect region)
  978. {
  979. if (_needsDisplay.IsEmpty)
  980. _needsDisplay = region;
  981. else {
  982. var x = Math.Min (_needsDisplay.X, region.X);
  983. var y = Math.Min (_needsDisplay.Y, region.Y);
  984. var w = Math.Max (_needsDisplay.Width, region.Width);
  985. var h = Math.Max (_needsDisplay.Height, region.Height);
  986. _needsDisplay = new Rect (x, y, w, h);
  987. }
  988. _superView?.SetSubViewNeedsDisplay ();
  989. if (subviews == null)
  990. return;
  991. foreach (var view in subviews)
  992. if (view.Frame.IntersectsWith (region)) {
  993. var childRegion = Rect.Intersect (view.Frame, region);
  994. childRegion.X -= view.Frame.X;
  995. childRegion.Y -= view.Frame.Y;
  996. view.SetNeedsDisplay (childRegion);
  997. }
  998. }
  999. private Rect GetNeedsDisplayRectScreen (Rect containerBounds)
  1000. {
  1001. Rect rect = ViewToScreen (_needsDisplay);
  1002. if (!containerBounds.IsEmpty) {
  1003. rect.Width = Math.Min (_needsDisplay.Width, containerBounds.Width);
  1004. rect.Height = Math.Min (_needsDisplay.Height, containerBounds.Height);
  1005. }
  1006. return rect;
  1007. }
  1008. internal bool _childNeedsDisplay { get; private set; }
  1009. /// <summary>
  1010. /// Indicates that any Subviews (in the <see cref="Subviews"/> list) need to be repainted.
  1011. /// </summary>
  1012. public void SetSubViewNeedsDisplay ()
  1013. {
  1014. _childNeedsDisplay = true;
  1015. if (_superView != null)
  1016. _superView.SetSubViewNeedsDisplay ();
  1017. }
  1018. internal bool addingView;
  1019. /// <summary>
  1020. /// Adds a subview (child) to this view.
  1021. /// </summary>
  1022. /// <remarks>
  1023. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property.
  1024. /// See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  1025. /// </remarks>
  1026. public virtual void Add (View view)
  1027. {
  1028. if (view == null) {
  1029. return;
  1030. }
  1031. if (subviews == null) {
  1032. subviews = new List<View> ();
  1033. }
  1034. if (tabIndexes == null) {
  1035. tabIndexes = new List<View> ();
  1036. }
  1037. subviews.Add (view);
  1038. tabIndexes.Add (view);
  1039. view._superView = this;
  1040. if (view.CanFocus) {
  1041. addingView = true;
  1042. if (SuperView?.CanFocus == false) {
  1043. SuperView.addingView = true;
  1044. SuperView.CanFocus = true;
  1045. SuperView.addingView = false;
  1046. }
  1047. CanFocus = true;
  1048. view.tabIndex = tabIndexes.IndexOf (view);
  1049. addingView = false;
  1050. }
  1051. if (view.Enabled && !Enabled) {
  1052. view.oldEnabled = true;
  1053. view.Enabled = false;
  1054. }
  1055. SetNeedsLayout ();
  1056. SetNeedsDisplay ();
  1057. OnAdded (new SuperViewChangedEventArgs (this, view));
  1058. if (IsInitialized && !view.IsInitialized) {
  1059. view.BeginInit ();
  1060. view.EndInit ();
  1061. }
  1062. }
  1063. /// <summary>
  1064. /// Adds the specified views (children) to the view.
  1065. /// </summary>
  1066. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  1067. /// <remarks>
  1068. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property.
  1069. /// See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  1070. /// </remarks>
  1071. public void Add (params View [] views)
  1072. {
  1073. if (views == null) {
  1074. return;
  1075. }
  1076. foreach (var view in views) {
  1077. Add (view);
  1078. }
  1079. }
  1080. /// <summary>
  1081. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  1082. /// </summary>
  1083. public virtual void RemoveAll ()
  1084. {
  1085. if (subviews == null) {
  1086. return;
  1087. }
  1088. while (subviews.Count > 0) {
  1089. Remove (subviews [0]);
  1090. }
  1091. }
  1092. /// <summary>
  1093. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  1094. /// </summary>
  1095. /// <remarks>
  1096. /// </remarks>
  1097. public virtual void Remove (View view)
  1098. {
  1099. if (view == null || subviews == null) return;
  1100. var touched = view.Frame;
  1101. subviews.Remove (view);
  1102. tabIndexes.Remove (view);
  1103. view._superView = null;
  1104. view.tabIndex = -1;
  1105. SetNeedsLayout ();
  1106. SetNeedsDisplay ();
  1107. if (subviews.Count < 1) CanFocus = false;
  1108. foreach (var v in subviews) {
  1109. if (v.Frame.IntersectsWith (touched))
  1110. view.SetNeedsDisplay ();
  1111. }
  1112. OnRemoved (new SuperViewChangedEventArgs (this, view));
  1113. if (focused == view) {
  1114. focused = null;
  1115. }
  1116. }
  1117. void PerformActionForSubview (View subview, Action<View> action)
  1118. {
  1119. if (subviews.Contains (subview)) {
  1120. action (subview);
  1121. }
  1122. SetNeedsDisplay ();
  1123. subview.SetNeedsDisplay ();
  1124. }
  1125. /// <summary>
  1126. /// Brings the specified subview to the front so it is drawn on top of any other views.
  1127. /// </summary>
  1128. /// <param name="subview">The subview to send to the front</param>
  1129. /// <remarks>
  1130. /// <seealso cref="SendSubviewToBack"/>.
  1131. /// </remarks>
  1132. public void BringSubviewToFront (View subview)
  1133. {
  1134. PerformActionForSubview (subview, x => {
  1135. subviews.Remove (x);
  1136. subviews.Add (x);
  1137. });
  1138. }
  1139. /// <summary>
  1140. /// Sends the specified subview to the front so it is the first view drawn
  1141. /// </summary>
  1142. /// <param name="subview">The subview to send to the front</param>
  1143. /// <remarks>
  1144. /// <seealso cref="BringSubviewToFront(View)"/>.
  1145. /// </remarks>
  1146. public void SendSubviewToBack (View subview)
  1147. {
  1148. PerformActionForSubview (subview, x => {
  1149. subviews.Remove (x);
  1150. subviews.Insert (0, subview);
  1151. });
  1152. }
  1153. /// <summary>
  1154. /// Moves the subview backwards in the hierarchy, only one step
  1155. /// </summary>
  1156. /// <param name="subview">The subview to send backwards</param>
  1157. /// <remarks>
  1158. /// If you want to send the view all the way to the back use SendSubviewToBack.
  1159. /// </remarks>
  1160. public void SendSubviewBackwards (View subview)
  1161. {
  1162. PerformActionForSubview (subview, x => {
  1163. var idx = subviews.IndexOf (x);
  1164. if (idx > 0) {
  1165. subviews.Remove (x);
  1166. subviews.Insert (idx - 1, x);
  1167. }
  1168. });
  1169. }
  1170. /// <summary>
  1171. /// Moves the subview backwards in the hierarchy, only one step
  1172. /// </summary>
  1173. /// <param name="subview">The subview to send backwards</param>
  1174. /// <remarks>
  1175. /// If you want to send the view all the way to the back use SendSubviewToBack.
  1176. /// </remarks>
  1177. public void BringSubviewForward (View subview)
  1178. {
  1179. PerformActionForSubview (subview, x => {
  1180. var idx = subviews.IndexOf (x);
  1181. if (idx + 1 < subviews.Count) {
  1182. subviews.Remove (x);
  1183. subviews.Insert (idx + 1, x);
  1184. }
  1185. });
  1186. }
  1187. /// <summary>
  1188. /// Clears the view region with the current color.
  1189. /// </summary>
  1190. /// <remarks>
  1191. /// <para>
  1192. /// This clears the entire region used by this view.
  1193. /// </para>
  1194. /// </remarks>
  1195. public void Clear ()
  1196. {
  1197. var h = Frame.Height;
  1198. var w = Frame.Width;
  1199. for (var line = 0; line < h; line++) {
  1200. Move (0, line);
  1201. for (var col = 0; col < w; col++)
  1202. Driver.AddRune (' ');
  1203. }
  1204. }
  1205. // BUGBUG: Stupid that this takes screen-relative. We should have a tenet that says
  1206. // "View APIs only deal with View-relative coords".
  1207. /// <summary>
  1208. /// Clears the specified region with the current color.
  1209. /// </summary>
  1210. /// <remarks>
  1211. /// </remarks>
  1212. /// <param name="regionScreen">The screen-relative region to clear.</param>
  1213. public void Clear (Rect regionScreen)
  1214. {
  1215. var h = regionScreen.Height;
  1216. var w = regionScreen.Width;
  1217. for (var line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  1218. Driver.Move (regionScreen.X, line);
  1219. for (var col = 0; col < w; col++)
  1220. Driver.AddRune (' ');
  1221. }
  1222. }
  1223. /// <summary>
  1224. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  1225. /// </summary>
  1226. /// <returns>The mapped point.</returns>
  1227. /// <param name="x">X screen-coordinate point.</param>
  1228. /// <param name="y">Y screen-coordinate point.</param>
  1229. public Point ScreenToView (int x, int y)
  1230. {
  1231. if (SuperView == null) {
  1232. return new Point (x - Frame.X, y - frame.Y);
  1233. } else {
  1234. var parent = SuperView.ScreenToView (x, y);
  1235. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  1236. }
  1237. }
  1238. /// <summary>
  1239. /// Converts a point from screen-relative coordinates to bounds-relative coordinates.
  1240. /// </summary>
  1241. /// <returns>The mapped point.</returns>
  1242. /// <param name="x">X screen-coordinate point.</param>
  1243. /// <param name="y">Y screen-coordinate point.</param>
  1244. public Point ScreenToBounds (int x, int y)
  1245. {
  1246. if (SuperView == null) {
  1247. return new Point (x - Frame.X + GetBoundsOffset ().X, y - Frame.Y + GetBoundsOffset ().Y);
  1248. } else {
  1249. var parent = SuperView.ScreenToView (x, y);
  1250. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  1251. }
  1252. }
  1253. /// <summary>
  1254. /// Converts a view-relative location to a screen-relative location (col,row). The output is optionally clamped to the screen dimensions.
  1255. /// </summary>
  1256. /// <param name="col">View-relative column.</param>
  1257. /// <param name="row">View-relative row.</param>
  1258. /// <param name="rcol">Absolute column; screen-relative.</param>
  1259. /// <param name="rrow">Absolute row; screen-relative.</param>
  1260. /// <param name="clamped">If <see langword="true"/>, <paramref name="rcol"/> and <paramref name="rrow"/> will be clamped to the
  1261. /// screen dimensions (they never be negative and will always be less than to <see cref="ConsoleDriver.Cols"/> and
  1262. /// <see cref="ConsoleDriver.Rows"/>, respectively.</param>
  1263. public virtual void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clamped = true)
  1264. {
  1265. rcol = col + Frame.X + GetBoundsOffset ().X;
  1266. rrow = row + Frame.Y + GetBoundsOffset ().Y;
  1267. var super = SuperView;
  1268. while (super != null) {
  1269. rcol += super.Frame.X + super.GetBoundsOffset ().X;
  1270. rrow += super.Frame.Y + super.GetBoundsOffset ().Y;
  1271. super = super.SuperView;
  1272. }
  1273. // The following ensures that the cursor is always in the screen boundaries.
  1274. if (clamped) {
  1275. rrow = Math.Min (rrow, Driver.Rows - 1);
  1276. rcol = Math.Min (rcol, Driver.Cols - 1);
  1277. }
  1278. }
  1279. /// <summary>
  1280. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  1281. /// </summary>
  1282. internal Rect ViewToScreen (Rect region)
  1283. {
  1284. ViewToScreen (region.X, region.Y, out var x, out var y, clamped: false);
  1285. return new Rect (x, y, region.Width, region.Height);
  1286. }
  1287. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  1288. internal Rect ScreenClip (Rect regionScreen)
  1289. {
  1290. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  1291. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  1292. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  1293. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  1294. return new Rect (x, y, w, h);
  1295. }
  1296. /// <summary>
  1297. /// Sets the <see cref="ConsoleDriver"/>'s clip region to <see cref="Bounds"/>.
  1298. /// </summary>
  1299. /// <returns>The current screen-relative clip region, which can be then re-applied by setting <see cref="ConsoleDriver.Clip"/>.</returns>
  1300. /// <remarks>
  1301. /// <para>
  1302. /// <see cref="Bounds"/> is View-relative.
  1303. /// </para>
  1304. /// <para>
  1305. /// If <see cref="ConsoleDriver.Clip"/> and <see cref="Bounds"/> do not intersect, the clip region will be set to <see cref="Rect.Empty"/>.
  1306. /// </para>
  1307. /// </remarks>
  1308. public Rect ClipToBounds ()
  1309. {
  1310. var clip = Bounds;
  1311. return SetClip (clip);
  1312. }
  1313. // BUGBUG: v2 - SetClip should return VIEW-relative so that it can be used to reset it; using Driver.Clip directly should not be necessary.
  1314. /// <summary>
  1315. /// Sets the clip region to the specified view-relative region.
  1316. /// </summary>
  1317. /// <returns>The current screen-relative clip region, which can be then re-applied by setting <see cref="ConsoleDriver.Clip"/>.</returns>
  1318. /// <param name="region">View-relative clip region.</param>
  1319. /// <remarks>
  1320. /// If <see cref="ConsoleDriver.Clip"/> and <paramref name="region"/> do not intersect, the clip region will be set to <see cref="Rect.Empty"/>.
  1321. /// </remarks>
  1322. public Rect SetClip (Rect region)
  1323. {
  1324. var previous = Driver.Clip;
  1325. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  1326. return previous;
  1327. }
  1328. /// <summary>
  1329. /// Draws a frame in the current view, clipped by the boundary of this view
  1330. /// </summary>
  1331. /// <param name="region">View-relative region for the frame to be drawn.</param>
  1332. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  1333. /// <param name="fill">If set to <see langword="true"/> it fill will the contents.</param>
  1334. [ObsoleteAttribute ("This method is obsolete in v2. Use use LineCanvas or Frame instead instead.", false)]
  1335. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  1336. {
  1337. var scrRect = ViewToScreen (region);
  1338. var savedClip = ClipToBounds ();
  1339. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  1340. Driver.Clip = savedClip;
  1341. }
  1342. /// <summary>
  1343. /// Utility function to draw strings that contain a hotkey.
  1344. /// </summary>
  1345. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  1346. /// <param name="hotColor">Hot color.</param>
  1347. /// <param name="normalColor">Normal color.</param>
  1348. /// <remarks>
  1349. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  1350. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  1351. /// </remarks>
  1352. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  1353. {
  1354. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  1355. Application.Driver.SetAttribute (normalColor);
  1356. foreach (var rune in text) {
  1357. if (rune == hotkeySpec) {
  1358. Application.Driver.SetAttribute (hotColor);
  1359. continue;
  1360. }
  1361. Application.Driver.AddRune (rune);
  1362. Application.Driver.SetAttribute (normalColor);
  1363. }
  1364. }
  1365. /// <summary>
  1366. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  1367. /// </summary>
  1368. /// <param name="text">String to display, the underscore before a letter flags the next letter as the hotkey.</param>
  1369. /// <param name="focused">If set to <see langword="true"/> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  1370. /// <param name="scheme">The color scheme to use.</param>
  1371. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  1372. {
  1373. if (focused)
  1374. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  1375. else
  1376. DrawHotString (text, Enabled ? scheme.HotNormal : scheme.Disabled, Enabled ? scheme.Normal : scheme.Disabled);
  1377. }
  1378. /// <summary>
  1379. /// This moves the cursor to the specified column and row in the view.
  1380. /// </summary>
  1381. /// <returns>The move.</returns>
  1382. /// <param name="col">The column to move to, in view-relative coordinates.</param>
  1383. /// <param name="row">the row to move to, in view-relative coordinates.</param>
  1384. /// <param name="clipped">Whether to clip the result of the ViewToScreen method,
  1385. /// If <see langword="true"/>, the <paramref name="col"/> and <paramref name="row"/> values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).</param>
  1386. public void Move (int col, int row, bool clipped = true)
  1387. {
  1388. if (Driver.Rows == 0) {
  1389. return;
  1390. }
  1391. ViewToScreen (col, row, out var rCol, out var rRow, clipped);
  1392. Driver.Move (rCol, rRow);
  1393. }
  1394. /// <summary>
  1395. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1396. /// </summary>
  1397. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1398. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1399. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1400. /// the last focused view. Views should make sure that they place the cursor
  1401. /// in a visually sensible place.
  1402. public virtual void PositionCursor ()
  1403. {
  1404. if (!CanBeVisible (this) || !Enabled) {
  1405. return;
  1406. }
  1407. // BUGBUG: v2 - This needs to support children of Frames too
  1408. if (focused == null && SuperView != null) {
  1409. SuperView.EnsureFocus ();
  1410. } else if (focused?.Visible == true && focused?.Enabled == true && focused?.Frame.Width > 0 && focused.Frame.Height > 0) {
  1411. focused.PositionCursor ();
  1412. } else if (focused?.Visible == true && focused?.Enabled == false) {
  1413. focused = null;
  1414. } else if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
  1415. Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
  1416. } else {
  1417. Move (frame.X, frame.Y);
  1418. }
  1419. }
  1420. // BUGBUG: v2 - Seems weird that this is in View and not Responder.
  1421. bool _hasFocus;
  1422. /// <inheritdoc/>
  1423. public override bool HasFocus => _hasFocus;
  1424. void SetHasFocus (bool value, View view, bool force = false)
  1425. {
  1426. if (_hasFocus != value || force) {
  1427. _hasFocus = value;
  1428. if (value) {
  1429. OnEnter (view);
  1430. } else {
  1431. OnLeave (view);
  1432. }
  1433. SetNeedsDisplay ();
  1434. }
  1435. // Remove focus down the chain of subviews if focus is removed
  1436. if (!value && focused != null) {
  1437. var f = focused;
  1438. f.OnLeave (view);
  1439. f.SetHasFocus (false, view);
  1440. focused = null;
  1441. }
  1442. }
  1443. /// <summary>
  1444. /// Method invoked when a subview is being added to this view.
  1445. /// </summary>
  1446. /// <param name="e">Event where <see cref="ViewEventArgs.View"/> is the subview being added.</param>
  1447. public virtual void OnAdded (SuperViewChangedEventArgs e)
  1448. {
  1449. var view = e.Child;
  1450. view.IsAdded = true;
  1451. view.x ??= view.frame.X;
  1452. view.y ??= view.frame.Y;
  1453. view.width ??= view.frame.Width;
  1454. view.height ??= view.frame.Height;
  1455. view.Added?.Invoke (this, e);
  1456. }
  1457. /// <summary>
  1458. /// Method invoked when a subview is being removed from this view.
  1459. /// </summary>
  1460. /// <param name="e">Event args describing the subview being removed.</param>
  1461. public virtual void OnRemoved (SuperViewChangedEventArgs e)
  1462. {
  1463. var view = e.Child;
  1464. view.IsAdded = false;
  1465. view.Removed?.Invoke (this, e);
  1466. }
  1467. /// <inheritdoc/>
  1468. public override bool OnEnter (View view)
  1469. {
  1470. var args = new FocusEventArgs (view);
  1471. Enter?.Invoke (this, args);
  1472. if (args.Handled)
  1473. return true;
  1474. if (base.OnEnter (view))
  1475. return true;
  1476. return false;
  1477. }
  1478. /// <inheritdoc/>
  1479. public override bool OnLeave (View view)
  1480. {
  1481. var args = new FocusEventArgs (view);
  1482. Leave?.Invoke (this, args);
  1483. if (args.Handled)
  1484. return true;
  1485. if (base.OnLeave (view))
  1486. return true;
  1487. return false;
  1488. }
  1489. /// <summary>
  1490. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1491. /// </summary>
  1492. /// <value>The focused.</value>
  1493. public View Focused => focused;
  1494. /// <summary>
  1495. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1496. /// </summary>
  1497. /// <value>The most focused View.</value>
  1498. public View MostFocused {
  1499. get {
  1500. if (Focused == null)
  1501. return null;
  1502. var most = Focused.MostFocused;
  1503. if (most != null)
  1504. return most;
  1505. return Focused;
  1506. }
  1507. }
  1508. ColorScheme colorScheme;
  1509. /// <summary>
  1510. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1511. /// color scheme.
  1512. /// </summary>
  1513. public virtual ColorScheme ColorScheme {
  1514. get {
  1515. if (colorScheme == null) {
  1516. return SuperView?.ColorScheme;
  1517. }
  1518. return colorScheme;
  1519. }
  1520. set {
  1521. if (colorScheme != value) {
  1522. colorScheme = value;
  1523. SetNeedsDisplay ();
  1524. }
  1525. }
  1526. }
  1527. /// <summary>
  1528. /// Displays the specified character in the specified column and row of the View.
  1529. /// </summary>
  1530. /// <param name="col">Column (view-relative).</param>
  1531. /// <param name="row">Row (view-relative).</param>
  1532. /// <param name="ch">Ch.</param>
  1533. public void AddRune (int col, int row, Rune ch)
  1534. {
  1535. if (row < 0 || col < 0)
  1536. return;
  1537. if (row > frame.Height - 1 || col > frame.Width - 1)
  1538. return;
  1539. Move (col, row);
  1540. Driver.AddRune (ch);
  1541. }
  1542. /// <summary>
  1543. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="_childNeedsDisplay"/> setting on this view.
  1544. /// </summary>
  1545. protected void ClearNeedsDisplay ()
  1546. {
  1547. _needsDisplay = Rect.Empty;
  1548. _childNeedsDisplay = false;
  1549. }
  1550. // TODO: Make this cancelable
  1551. /// <summary>
  1552. ///
  1553. /// </summary>
  1554. /// <returns></returns>
  1555. public virtual bool OnDrawFrames (Rect bounds)
  1556. {
  1557. var prevClip = Driver.Clip;
  1558. if (SuperView != null) {
  1559. Driver.Clip = SuperView.ClipToBounds ();
  1560. }
  1561. Margin?.Redraw (Margin.Frame);
  1562. BorderFrame?.Redraw (BorderFrame.Frame);
  1563. Padding?.Redraw (Padding.Frame);
  1564. Driver.Clip = prevClip;
  1565. return true;
  1566. }
  1567. /// <summary>
  1568. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1569. /// </summary>
  1570. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1571. /// <remarks>
  1572. /// <para>
  1573. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1574. /// </para>
  1575. /// <para>
  1576. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1577. /// the last color that was set globally on the driver.
  1578. /// </para>
  1579. /// <para>
  1580. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1581. /// larger than the <ref name="bounds"/> parameter, as this will cause the driver to clip the entire region.
  1582. /// </para>
  1583. /// </remarks>
  1584. public virtual void Redraw (Rect bounds)
  1585. {
  1586. if (!CanBeVisible (this)) {
  1587. return;
  1588. }
  1589. OnDrawFrames (Frame);
  1590. var prevClip = ClipToBounds ();
  1591. // TODO: Implement complete event
  1592. // OnDrawFramesComplete (Frame)
  1593. if (ColorScheme != null) {
  1594. //Driver.SetAttribute (HasFocus ? GetFocusColor () : GetNormalColor ());
  1595. Driver.SetAttribute (GetNormalColor ());
  1596. }
  1597. Clear (ViewToScreen (bounds));
  1598. // Invoke DrawContentEvent
  1599. OnDrawContent (bounds);
  1600. // Draw subviews
  1601. // TODO: Implement OnDrawSubviews (cancelable);
  1602. if (subviews != null) {
  1603. foreach (var view in subviews) {
  1604. if (true) { //!view._needsDisplay.IsEmpty || view._childNeedsDisplay || view.LayoutNeeded) {
  1605. if (true) { //view.Frame.IntersectsWith (bounds)) { // && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1606. if (view.LayoutNeeded) {
  1607. view.LayoutSubviews ();
  1608. }
  1609. // Draw the subview
  1610. // Use the view's bounds (view-relative; Location will always be (0,0)
  1611. //if (view.Visible && view.Frame.Width > 0 && view.Frame.Height > 0) {
  1612. view.Redraw (view.Bounds);
  1613. //}
  1614. }
  1615. view.ClearNeedsDisplay ();
  1616. }
  1617. }
  1618. }
  1619. // Invoke DrawContentCompleteEvent
  1620. OnDrawContentComplete (bounds);
  1621. // BUGBUG: v2 - We should be able to use View.SetClip here and not have to resort to knowing Driver details.
  1622. Driver.Clip = prevClip;
  1623. ClearLayoutNeeded ();
  1624. ClearNeedsDisplay ();
  1625. }
  1626. /// <summary>
  1627. /// Event invoked when the content area of the View is to be drawn.
  1628. /// </summary>
  1629. /// <remarks>
  1630. /// <para>
  1631. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1632. /// </para>
  1633. /// <para>
  1634. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1635. /// </para>
  1636. /// </remarks>
  1637. public event EventHandler<DrawEventArgs> DrawContent;
  1638. /// <summary>
  1639. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1640. /// </summary>
  1641. /// <param name="contentArea">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1642. /// <remarks>
  1643. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1644. /// </remarks>
  1645. public virtual void OnDrawContent (Rect contentArea)
  1646. {
  1647. // TODO: Make DrawContent a cancelable event
  1648. // if (!DrawContent?.Invoke(this, new DrawEventArgs (viewport)) {
  1649. DrawContent?.Invoke (this, new DrawEventArgs (contentArea));
  1650. if (!ustring.IsNullOrEmpty (TextFormatter.Text)) {
  1651. if (TextFormatter != null) {
  1652. TextFormatter.NeedsFormat = true;
  1653. }
  1654. TextFormatter?.Draw (ViewToScreen (contentArea), HasFocus ? GetFocusColor () : GetNormalColor (),
  1655. HasFocus ? ColorScheme.HotFocus : GetHotNormalColor (),
  1656. new Rect (ViewToScreen (contentArea).Location, Bounds.Size), true);
  1657. SetSubViewNeedsDisplay ();
  1658. }
  1659. }
  1660. /// <summary>
  1661. /// Event invoked when the content area of the View is completed drawing.
  1662. /// </summary>
  1663. /// <remarks>
  1664. /// <para>
  1665. /// Will be invoked after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1666. /// </para>
  1667. /// <para>
  1668. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1669. /// </para>
  1670. /// </remarks>
  1671. public event EventHandler<DrawEventArgs> DrawContentComplete;
  1672. /// <summary>
  1673. /// Enables overrides after completed drawing infinitely scrolled content and/or a background behind removed controls.
  1674. /// </summary>
  1675. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1676. /// <remarks>
  1677. /// This method will be called after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1678. /// </remarks>
  1679. public virtual void OnDrawContentComplete (Rect viewport)
  1680. {
  1681. DrawContentComplete?.Invoke (this, new DrawEventArgs (viewport));
  1682. }
  1683. /// <summary>
  1684. /// Causes the specified subview to have focus.
  1685. /// </summary>
  1686. /// <param name="view">View.</param>
  1687. void SetFocus (View view)
  1688. {
  1689. if (view == null)
  1690. return;
  1691. //Console.WriteLine ($"Request to focus {view}");
  1692. if (!view.CanFocus || !view.Visible || !view.Enabled)
  1693. return;
  1694. if (focused?._hasFocus == true && focused == view)
  1695. return;
  1696. // Make sure that this view is a subview
  1697. View c;
  1698. for (c = view._superView; c != null; c = c._superView)
  1699. if (c == this)
  1700. break;
  1701. if (c == null)
  1702. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1703. if (focused != null)
  1704. focused.SetHasFocus (false, view);
  1705. var f = focused;
  1706. focused = view;
  1707. focused.SetHasFocus (true, f);
  1708. focused.EnsureFocus ();
  1709. // Send focus upwards
  1710. SuperView?.SetFocus (this);
  1711. }
  1712. /// <summary>
  1713. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  1714. /// </summary>
  1715. public void SetFocus ()
  1716. {
  1717. if (!CanBeVisible (this) || !Enabled) {
  1718. if (HasFocus) {
  1719. SetHasFocus (false, this);
  1720. }
  1721. return;
  1722. }
  1723. SuperView?.SetFocus (this);
  1724. }
  1725. /// <summary>
  1726. /// Invoked when a character key is pressed and occurs after the key up event.
  1727. /// </summary>
  1728. public event EventHandler<KeyEventEventArgs> KeyPress;
  1729. /// <inheritdoc/>
  1730. public override bool ProcessKey (KeyEvent keyEvent)
  1731. {
  1732. if (!Enabled) {
  1733. return false;
  1734. }
  1735. var args = new KeyEventEventArgs (keyEvent);
  1736. KeyPress?.Invoke (this, args);
  1737. if (args.Handled)
  1738. return true;
  1739. if (Focused?.Enabled == true) {
  1740. Focused?.KeyPress?.Invoke (this, args);
  1741. if (args.Handled)
  1742. return true;
  1743. }
  1744. return Focused?.Enabled == true && Focused?.ProcessKey (keyEvent) == true;
  1745. }
  1746. /// <summary>
  1747. /// Invokes any binding that is registered on this <see cref="View"/>
  1748. /// and matches the <paramref name="keyEvent"/>
  1749. /// </summary>
  1750. /// <param name="keyEvent">The key event passed.</param>
  1751. protected bool? InvokeKeybindings (KeyEvent keyEvent)
  1752. {
  1753. bool? toReturn = null;
  1754. if (KeyBindings.ContainsKey (keyEvent.Key)) {
  1755. foreach (var command in KeyBindings [keyEvent.Key]) {
  1756. if (!CommandImplementations.ContainsKey (command)) {
  1757. 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})");
  1758. }
  1759. // each command has its own return value
  1760. var thisReturn = CommandImplementations [command] ();
  1761. // if we haven't got anything yet, the current command result should be used
  1762. if (toReturn == null) {
  1763. toReturn = thisReturn;
  1764. }
  1765. // if ever see a true then that's what we will return
  1766. if (thisReturn ?? false) {
  1767. toReturn = true;
  1768. }
  1769. }
  1770. }
  1771. return toReturn;
  1772. }
  1773. /// <summary>
  1774. /// <para>Adds a new key combination that will trigger the given <paramref name="command"/>
  1775. /// (if supported by the View - see <see cref="GetSupportedCommands"/>)
  1776. /// </para>
  1777. /// <para>If the key is already bound to a different <see cref="Command"/> it will be
  1778. /// rebound to this one</para>
  1779. /// <remarks>Commands are only ever applied to the current <see cref="View"/>(i.e. this feature
  1780. /// cannot be used to switch focus to another view and perform multiple commands there) </remarks>
  1781. /// </summary>
  1782. /// <param name="key"></param>
  1783. /// <param name="command">The command(s) to run on the <see cref="View"/> when <paramref name="key"/> is pressed.
  1784. /// When specifying multiple commands, all commands will be applied in sequence. The bound <paramref name="key"/> strike
  1785. /// will be consumed if any took effect.</param>
  1786. public void AddKeyBinding (Key key, params Command [] command)
  1787. {
  1788. if (command.Length == 0) {
  1789. throw new ArgumentException ("At least one command must be specified", nameof (command));
  1790. }
  1791. if (KeyBindings.ContainsKey (key)) {
  1792. KeyBindings [key] = command;
  1793. } else {
  1794. KeyBindings.Add (key, command);
  1795. }
  1796. }
  1797. /// <summary>
  1798. /// Replaces a key combination already bound to <see cref="Command"/>.
  1799. /// </summary>
  1800. /// <param name="fromKey">The key to be replaced.</param>
  1801. /// <param name="toKey">The new key to be used.</param>
  1802. protected void ReplaceKeyBinding (Key fromKey, Key toKey)
  1803. {
  1804. if (KeyBindings.ContainsKey (fromKey)) {
  1805. var value = KeyBindings [fromKey];
  1806. KeyBindings.Remove (fromKey);
  1807. KeyBindings [toKey] = value;
  1808. }
  1809. }
  1810. /// <summary>
  1811. /// Checks if the key binding already exists.
  1812. /// </summary>
  1813. /// <param name="key">The key to check.</param>
  1814. /// <returns><see langword="true"/> If the key already exist, <see langword="false"/> otherwise.</returns>
  1815. public bool ContainsKeyBinding (Key key)
  1816. {
  1817. return KeyBindings.ContainsKey (key);
  1818. }
  1819. /// <summary>
  1820. /// Removes all bound keys from the View and resets the default bindings.
  1821. /// </summary>
  1822. public void ClearKeybindings ()
  1823. {
  1824. KeyBindings.Clear ();
  1825. }
  1826. /// <summary>
  1827. /// Clears the existing keybinding (if any) for the given <paramref name="key"/>.
  1828. /// </summary>
  1829. /// <param name="key"></param>
  1830. public void ClearKeybinding (Key key)
  1831. {
  1832. KeyBindings.Remove (key);
  1833. }
  1834. /// <summary>
  1835. /// Removes all key bindings that trigger the given command. Views can have multiple different
  1836. /// keys bound to the same command and this method will clear all of them.
  1837. /// </summary>
  1838. /// <param name="command"></param>
  1839. public void ClearKeybinding (params Command [] command)
  1840. {
  1841. foreach (var kvp in KeyBindings.Where (kvp => kvp.Value.SequenceEqual (command)).ToArray ()) {
  1842. KeyBindings.Remove (kvp.Key);
  1843. }
  1844. }
  1845. /// <summary>
  1846. /// <para>States that the given <see cref="View"/> supports a given <paramref name="command"/>
  1847. /// and what <paramref name="f"/> to perform to make that command happen
  1848. /// </para>
  1849. /// <para>If the <paramref name="command"/> already has an implementation the <paramref name="f"/>
  1850. /// will replace the old one</para>
  1851. /// </summary>
  1852. /// <param name="command">The command.</param>
  1853. /// <param name="f">The function.</param>
  1854. protected void AddCommand (Command command, Func<bool?> f)
  1855. {
  1856. // if there is already an implementation of this command
  1857. if (CommandImplementations.ContainsKey (command)) {
  1858. // replace that implementation
  1859. CommandImplementations [command] = f;
  1860. } else {
  1861. // else record how to perform the action (this should be the normal case)
  1862. CommandImplementations.Add (command, f);
  1863. }
  1864. }
  1865. /// <summary>
  1866. /// Returns all commands that are supported by this <see cref="View"/>.
  1867. /// </summary>
  1868. /// <returns></returns>
  1869. public IEnumerable<Command> GetSupportedCommands ()
  1870. {
  1871. return CommandImplementations.Keys;
  1872. }
  1873. /// <summary>
  1874. /// Gets the key used by a command.
  1875. /// </summary>
  1876. /// <param name="command">The command to search.</param>
  1877. /// <returns>The <see cref="Key"/> used by a <see cref="Command"/></returns>
  1878. public Key GetKeyFromCommand (params Command [] command)
  1879. {
  1880. return KeyBindings.First (kb => kb.Value.SequenceEqual (command)).Key;
  1881. }
  1882. /// <inheritdoc/>
  1883. public override bool ProcessHotKey (KeyEvent keyEvent)
  1884. {
  1885. if (!Enabled) {
  1886. return false;
  1887. }
  1888. var args = new KeyEventEventArgs (keyEvent);
  1889. if (MostFocused?.Enabled == true) {
  1890. MostFocused?.KeyPress?.Invoke (this, args);
  1891. if (args.Handled)
  1892. return true;
  1893. }
  1894. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1895. return true;
  1896. if (subviews == null || subviews.Count == 0)
  1897. return false;
  1898. foreach (var view in subviews)
  1899. if (view.Enabled && view.ProcessHotKey (keyEvent))
  1900. return true;
  1901. return false;
  1902. }
  1903. /// <inheritdoc/>
  1904. public override bool ProcessColdKey (KeyEvent keyEvent)
  1905. {
  1906. if (!Enabled) {
  1907. return false;
  1908. }
  1909. var args = new KeyEventEventArgs (keyEvent);
  1910. KeyPress?.Invoke (this, args);
  1911. if (args.Handled)
  1912. return true;
  1913. if (MostFocused?.Enabled == true) {
  1914. MostFocused?.KeyPress?.Invoke (this, args);
  1915. if (args.Handled)
  1916. return true;
  1917. }
  1918. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1919. return true;
  1920. if (subviews == null || subviews.Count == 0)
  1921. return false;
  1922. foreach (var view in subviews)
  1923. if (view.Enabled && view.ProcessColdKey (keyEvent))
  1924. return true;
  1925. return false;
  1926. }
  1927. /// <summary>
  1928. /// Invoked when a key is pressed.
  1929. /// </summary>
  1930. public event EventHandler<KeyEventEventArgs> KeyDown;
  1931. /// <inheritdoc/>
  1932. public override bool OnKeyDown (KeyEvent keyEvent)
  1933. {
  1934. if (!Enabled) {
  1935. return false;
  1936. }
  1937. var args = new KeyEventEventArgs (keyEvent);
  1938. KeyDown?.Invoke (this, args);
  1939. if (args.Handled) {
  1940. return true;
  1941. }
  1942. if (Focused?.Enabled == true) {
  1943. Focused.KeyDown?.Invoke (this, args);
  1944. if (args.Handled) {
  1945. return true;
  1946. }
  1947. if (Focused?.OnKeyDown (keyEvent) == true) {
  1948. return true;
  1949. }
  1950. }
  1951. return false;
  1952. }
  1953. /// <summary>
  1954. /// Invoked when a key is released.
  1955. /// </summary>
  1956. public event EventHandler<KeyEventEventArgs> KeyUp;
  1957. /// <inheritdoc/>
  1958. public override bool OnKeyUp (KeyEvent keyEvent)
  1959. {
  1960. if (!Enabled) {
  1961. return false;
  1962. }
  1963. var args = new KeyEventEventArgs (keyEvent);
  1964. KeyUp?.Invoke (this, args);
  1965. if (args.Handled) {
  1966. return true;
  1967. }
  1968. if (Focused?.Enabled == true) {
  1969. Focused.KeyUp?.Invoke (this, args);
  1970. if (args.Handled) {
  1971. return true;
  1972. }
  1973. if (Focused?.OnKeyUp (keyEvent) == true) {
  1974. return true;
  1975. }
  1976. }
  1977. return false;
  1978. }
  1979. /// <summary>
  1980. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, does nothing.
  1981. /// </summary>
  1982. public void EnsureFocus ()
  1983. {
  1984. if (focused == null && subviews?.Count > 0) {
  1985. if (FocusDirection == Direction.Forward) {
  1986. FocusFirst ();
  1987. } else {
  1988. FocusLast ();
  1989. }
  1990. }
  1991. }
  1992. /// <summary>
  1993. /// Focuses the first focusable subview if one exists.
  1994. /// </summary>
  1995. public void FocusFirst ()
  1996. {
  1997. if (!CanBeVisible (this)) {
  1998. return;
  1999. }
  2000. if (tabIndexes == null) {
  2001. SuperView?.SetFocus (this);
  2002. return;
  2003. }
  2004. foreach (var view in tabIndexes) {
  2005. if (view.CanFocus && view.tabStop && view.Visible && view.Enabled) {
  2006. SetFocus (view);
  2007. return;
  2008. }
  2009. }
  2010. }
  2011. /// <summary>
  2012. /// Focuses the last focusable subview if one exists.
  2013. /// </summary>
  2014. public void FocusLast ()
  2015. {
  2016. if (!CanBeVisible (this)) {
  2017. return;
  2018. }
  2019. if (tabIndexes == null) {
  2020. SuperView?.SetFocus (this);
  2021. return;
  2022. }
  2023. for (var i = tabIndexes.Count; i > 0;) {
  2024. i--;
  2025. var v = tabIndexes [i];
  2026. if (v.CanFocus && v.tabStop && v.Visible && v.Enabled) {
  2027. SetFocus (v);
  2028. return;
  2029. }
  2030. }
  2031. }
  2032. /// <summary>
  2033. /// Focuses the previous view.
  2034. /// </summary>
  2035. /// <returns><see langword="true"/> if previous was focused, <see langword="false"/> otherwise.</returns>
  2036. public bool FocusPrev ()
  2037. {
  2038. if (!CanBeVisible (this)) {
  2039. return false;
  2040. }
  2041. FocusDirection = Direction.Backward;
  2042. if (tabIndexes == null || tabIndexes.Count == 0)
  2043. return false;
  2044. if (focused == null) {
  2045. FocusLast ();
  2046. return focused != null;
  2047. }
  2048. var focusedIdx = -1;
  2049. for (var i = tabIndexes.Count; i > 0;) {
  2050. i--;
  2051. var w = tabIndexes [i];
  2052. if (w.HasFocus) {
  2053. if (w.FocusPrev ())
  2054. return true;
  2055. focusedIdx = i;
  2056. continue;
  2057. }
  2058. if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
  2059. focused.SetHasFocus (false, w);
  2060. if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  2061. w.FocusLast ();
  2062. SetFocus (w);
  2063. return true;
  2064. }
  2065. }
  2066. if (focused != null) {
  2067. focused.SetHasFocus (false, this);
  2068. focused = null;
  2069. }
  2070. return false;
  2071. }
  2072. /// <summary>
  2073. /// Focuses the next view.
  2074. /// </summary>
  2075. /// <returns><see langword="true"/> if next was focused, <see langword="false"/> otherwise.</returns>
  2076. public bool FocusNext ()
  2077. {
  2078. if (!CanBeVisible (this)) {
  2079. return false;
  2080. }
  2081. FocusDirection = Direction.Forward;
  2082. if (tabIndexes == null || tabIndexes.Count == 0)
  2083. return false;
  2084. if (focused == null) {
  2085. FocusFirst ();
  2086. return focused != null;
  2087. }
  2088. var n = tabIndexes.Count;
  2089. var focusedIdx = -1;
  2090. for (var i = 0; i < n; i++) {
  2091. var w = tabIndexes [i];
  2092. if (w.HasFocus) {
  2093. if (w.FocusNext ())
  2094. return true;
  2095. focusedIdx = i;
  2096. continue;
  2097. }
  2098. if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
  2099. focused.SetHasFocus (false, w);
  2100. if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  2101. w.FocusFirst ();
  2102. SetFocus (w);
  2103. return true;
  2104. }
  2105. }
  2106. if (focused != null) {
  2107. focused.SetHasFocus (false, this);
  2108. focused = null;
  2109. }
  2110. return false;
  2111. }
  2112. View GetMostFocused (View view)
  2113. {
  2114. if (view == null) {
  2115. return null;
  2116. }
  2117. return view.focused != null ? GetMostFocused (view.focused) : view;
  2118. }
  2119. /// <summary>
  2120. /// Sets the View's <see cref="Frame"/> to the frame-relative coordinates if its container. The
  2121. /// container size and location are specified by <paramref name="superviewFrame"/> and are relative to the
  2122. /// View's superview.
  2123. /// </summary>
  2124. /// <param name="superviewFrame">The supserview-relative rectangle describing View's container (nominally the
  2125. /// same as <c>this.SuperView.Frame</c>).</param>
  2126. internal void SetRelativeLayout (Rect superviewFrame)
  2127. {
  2128. int newX, newW, newY, newH;
  2129. var autosize = Size.Empty;
  2130. if (AutoSize) {
  2131. // Note this is global to this function and used as such within the local functions defined
  2132. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  2133. autosize = GetAutoSize ();
  2134. }
  2135. // Returns the new dimension (width or height) and location (x or y) for the View given
  2136. // the superview's Frame.X or Frame.Y
  2137. // the superview's width or height
  2138. // the current Pos (View.X or View.Y)
  2139. // the current Dim (View.Width or View.Height)
  2140. (int newLocation, int newDimension) GetNewLocationAndDimension (int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
  2141. {
  2142. int newDimension, newLocation;
  2143. switch (pos) {
  2144. case Pos.PosCenter:
  2145. if (dim == null) {
  2146. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  2147. } else {
  2148. newDimension = dim.Anchor (superviewDimension);
  2149. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  2150. }
  2151. newLocation = pos.Anchor (superviewDimension - newDimension);
  2152. break;
  2153. case Pos.PosCombine combine:
  2154. int left, right;
  2155. (left, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.left, dim, autosizeDimension);
  2156. (right, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.right, dim, autosizeDimension);
  2157. if (combine.add) {
  2158. newLocation = left + right;
  2159. } else {
  2160. newLocation = left - right;
  2161. }
  2162. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  2163. break;
  2164. case Pos.PosAbsolute:
  2165. case Pos.PosAnchorEnd:
  2166. case Pos.PosFactor:
  2167. case Pos.PosFunc:
  2168. case Pos.PosView:
  2169. default:
  2170. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  2171. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  2172. break;
  2173. }
  2174. return (newLocation, newDimension);
  2175. }
  2176. // Recursively calculates the new dimension (width or height) of the given Dim given:
  2177. // the current location (x or y)
  2178. // the current dimension (width or height)
  2179. int CalculateNewDimension (Dim d, int location, int dimension, int autosize)
  2180. {
  2181. int newDimension;
  2182. switch (d) {
  2183. case null:
  2184. newDimension = AutoSize ? autosize : dimension;
  2185. break;
  2186. case Dim.DimCombine combine:
  2187. int leftNewDim = CalculateNewDimension (combine.left, location, dimension, autosize);
  2188. int rightNewDim = CalculateNewDimension (combine.right, location, dimension, autosize);
  2189. if (combine.add) {
  2190. newDimension = leftNewDim + rightNewDim;
  2191. } else {
  2192. newDimension = leftNewDim - rightNewDim;
  2193. }
  2194. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2195. break;
  2196. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  2197. newDimension = d.Anchor (dimension);
  2198. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2199. break;
  2200. case Dim.DimFill:
  2201. default:
  2202. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  2203. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2204. break;
  2205. }
  2206. return newDimension;
  2207. }
  2208. // horizontal
  2209. (newX, newW) = GetNewLocationAndDimension (superviewFrame.X, superviewFrame.Width, x, width, autosize.Width);
  2210. // vertical
  2211. (newY, newH) = GetNewLocationAndDimension (superviewFrame.Y, superviewFrame.Height, y, height, autosize.Height);
  2212. var r = new Rect (newX, newY, newW, newH);
  2213. if (Frame != r) {
  2214. Frame = r;
  2215. // BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
  2216. if (!SetMinWidthHeight ()) {
  2217. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2218. }
  2219. }
  2220. }
  2221. /// <summary>
  2222. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2223. /// </summary>
  2224. /// <remarks>
  2225. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2226. /// </remarks>
  2227. public event EventHandler<LayoutEventArgs> LayoutStarted;
  2228. /// <summary>
  2229. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  2230. /// </summary>
  2231. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  2232. {
  2233. LayoutStarted?.Invoke (this, args);
  2234. }
  2235. /// <summary>
  2236. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2237. /// </summary>
  2238. /// <remarks>
  2239. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2240. /// </remarks>
  2241. public event EventHandler<LayoutEventArgs> LayoutComplete;
  2242. /// <summary>
  2243. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  2244. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  2245. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  2246. /// </summary>
  2247. public event EventHandler Initialized;
  2248. /// <summary>
  2249. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  2250. /// </summary>
  2251. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  2252. {
  2253. LayoutComplete?.Invoke (this, args);
  2254. }
  2255. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2256. {
  2257. switch (pos) {
  2258. case Pos.PosView pv:
  2259. // See #2461
  2260. //if (!from.InternalSubviews.Contains (pv.Target)) {
  2261. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  2262. //}
  2263. if (pv.Target != this) {
  2264. nEdges.Add ((pv.Target, from));
  2265. }
  2266. foreach (var v in from.InternalSubviews) {
  2267. CollectAll (v, ref nNodes, ref nEdges);
  2268. }
  2269. return;
  2270. case Pos.PosCombine pc:
  2271. foreach (var v in from.InternalSubviews) {
  2272. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  2273. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  2274. }
  2275. break;
  2276. }
  2277. }
  2278. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2279. {
  2280. switch (dim) {
  2281. case Dim.DimView dv:
  2282. // See #2461
  2283. //if (!from.InternalSubviews.Contains (dv.Target)) {
  2284. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  2285. //}
  2286. if (dv.Target != this) {
  2287. nEdges.Add ((dv.Target, from));
  2288. }
  2289. foreach (var v in from.InternalSubviews) {
  2290. CollectAll (v, ref nNodes, ref nEdges);
  2291. }
  2292. return;
  2293. case Dim.DimCombine dc:
  2294. foreach (var v in from.InternalSubviews) {
  2295. CollectDim (dc.left, from, ref nNodes, ref nEdges);
  2296. CollectDim (dc.right, from, ref nNodes, ref nEdges);
  2297. }
  2298. break;
  2299. }
  2300. }
  2301. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2302. {
  2303. foreach (var v in from.InternalSubviews) {
  2304. nNodes.Add (v);
  2305. if (v._layoutStyle != LayoutStyle.Computed) {
  2306. continue;
  2307. }
  2308. CollectPos (v.X, v, ref nNodes, ref nEdges);
  2309. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  2310. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  2311. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  2312. }
  2313. }
  2314. // https://en.wikipedia.org/wiki/Topological_sorting
  2315. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  2316. {
  2317. var result = new List<View> ();
  2318. // Set of all nodes with no incoming edges
  2319. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  2320. while (noEdgeNodes.Any ()) {
  2321. // remove a node n from S
  2322. var n = noEdgeNodes.First ();
  2323. noEdgeNodes.Remove (n);
  2324. // add n to tail of L
  2325. if (n != superView)
  2326. result.Add (n);
  2327. // for each node m with an edge e from n to m do
  2328. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  2329. var m = e.To;
  2330. // remove edge e from the graph
  2331. edges.Remove (e);
  2332. // if m has no other incoming edges then
  2333. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  2334. // insert m into S
  2335. noEdgeNodes.Add (m);
  2336. }
  2337. }
  2338. }
  2339. if (edges.Any ()) {
  2340. (var from, var to) = edges.First ();
  2341. if (from != superView?.GetTopSuperView (to, from)) {
  2342. if (!ReferenceEquals (from, to)) {
  2343. if (ReferenceEquals (from.SuperView, to)) {
  2344. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
  2345. } else {
  2346. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
  2347. }
  2348. } else {
  2349. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": A recursive cycle was found in the relative Pos/Dim of the SubViews.");
  2350. }
  2351. }
  2352. }
  2353. // return L (a topologically sorted order)
  2354. return result;
  2355. } // TopologicalSort
  2356. /// <summary>
  2357. /// Overriden by <see cref="Frame"/> to do nothing, as the <see cref="Frame"/> does not have frames.
  2358. /// </summary>
  2359. internal virtual void LayoutFrames ()
  2360. {
  2361. if (Margin == null) return; // CreateFrames() has not been called yet
  2362. Margin.X = 0;
  2363. Margin.Y = 0;
  2364. Margin.Width = Frame.Size.Width;
  2365. Margin.Height = Frame.Size.Height;
  2366. Margin.SetNeedsLayout ();
  2367. Margin.LayoutSubviews ();
  2368. Margin.SetNeedsDisplay ();
  2369. var border = Margin.Thickness.GetInside (Margin.Frame);
  2370. BorderFrame.X = border.Location.X;
  2371. BorderFrame.Y = border.Location.Y;
  2372. BorderFrame.Width = border.Size.Width;
  2373. BorderFrame.Height = border.Size.Height;
  2374. BorderFrame.SetNeedsLayout ();
  2375. BorderFrame.LayoutSubviews ();
  2376. BorderFrame.SetNeedsDisplay ();
  2377. var padding = BorderFrame.Thickness.GetInside (BorderFrame.Frame);
  2378. Padding.X = padding.Location.X;
  2379. Padding.Y = padding.Location.Y;
  2380. Padding.Width = padding.Size.Width;
  2381. Padding.Height = padding.Size.Height;
  2382. Padding.SetNeedsLayout ();
  2383. Padding.LayoutSubviews ();
  2384. Padding.SetNeedsDisplay ();
  2385. }
  2386. /// <summary>
  2387. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  2388. /// response to the container view or terminal resizing.
  2389. /// </summary>
  2390. /// <remarks>
  2391. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  2392. /// </remarks>
  2393. public virtual void LayoutSubviews ()
  2394. {
  2395. if (!LayoutNeeded) {
  2396. return;
  2397. }
  2398. LayoutFrames ();
  2399. var oldBounds = Bounds;
  2400. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  2401. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2402. // Sort out the dependencies of the X, Y, Width, Height properties
  2403. var nodes = new HashSet<View> ();
  2404. var edges = new HashSet<(View, View)> ();
  2405. CollectAll (this, ref nodes, ref edges);
  2406. var ordered = View.TopologicalSort (SuperView, nodes, edges);
  2407. foreach (var v in ordered) {
  2408. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  2409. }
  2410. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  2411. // Use LayoutSubview with the Frame of the 'from'
  2412. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded
  2413. && ordered.Count == 0 && edges.Count > 0 && LayoutStyle == LayoutStyle.Computed) {
  2414. (var from, var to) = edges.First ();
  2415. LayoutSubview (to, from.Frame);
  2416. }
  2417. LayoutNeeded = false;
  2418. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  2419. }
  2420. private void LayoutSubview (View v, Rect contentArea)
  2421. {
  2422. if (v.LayoutStyle == LayoutStyle.Computed) {
  2423. v.SetRelativeLayout (contentArea);
  2424. }
  2425. v.LayoutSubviews ();
  2426. v.LayoutNeeded = false;
  2427. }
  2428. ustring text;
  2429. /// <summary>
  2430. /// The text displayed by the <see cref="View"/>.
  2431. /// </summary>
  2432. /// <remarks>
  2433. /// <para>
  2434. /// If provided, the text will be drawn before any subviews are drawn.
  2435. /// </para>
  2436. /// <para>
  2437. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  2438. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  2439. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  2440. /// is 1, the text will be clipped.
  2441. /// </para>
  2442. /// <para>
  2443. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  2444. /// <c>(Rune)0xffff</c>.
  2445. /// </para>
  2446. /// </remarks>
  2447. public virtual ustring Text {
  2448. get => text;
  2449. set {
  2450. text = value;
  2451. if (IsInitialized) {
  2452. SetHotKey ();
  2453. UpdateTextFormatterText ();
  2454. OnResizeNeeded ();
  2455. }
  2456. // BUGBUG: v2 - This is here as a HACK until we fix the unit tests to not check a view's dims until
  2457. // after it's been initialized. See #2450
  2458. UpdateTextFormatterText ();
  2459. #if DEBUG
  2460. if (text != null && string.IsNullOrEmpty (Id)) {
  2461. Id = text.ToString ();
  2462. }
  2463. #endif
  2464. }
  2465. }
  2466. /// <summary>
  2467. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  2468. /// within <see cref="Bounds"/>
  2469. /// <para>
  2470. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If <see langword="true"/> then
  2471. /// <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can fit;
  2472. /// if <see cref="Text"/> won't fit the view will be resized as needed.
  2473. /// </para>
  2474. /// <para>
  2475. /// In addition, if <see cref="ForceValidatePosDim"/> is <see langword="true"/> the new values of <see cref="Width"/> and
  2476. /// <see cref="Height"/> must be of the same types of the existing one to avoid breaking the <see cref="Dim"/> settings.
  2477. /// </para>
  2478. /// </summary>
  2479. public virtual bool AutoSize {
  2480. get => autoSize;
  2481. set {
  2482. var v = ResizeView (value);
  2483. TextFormatter.AutoSize = v;
  2484. if (autoSize != v) {
  2485. autoSize = v;
  2486. TextFormatter.NeedsFormat = true;
  2487. UpdateTextFormatterText ();
  2488. OnResizeNeeded ();
  2489. }
  2490. }
  2491. }
  2492. /// <summary>
  2493. /// Gets or sets a flag that determines whether <see cref="Terminal.Gui.TextFormatter.Text"/> will have trailing spaces preserved
  2494. /// or not when <see cref="Terminal.Gui.TextFormatter.WordWrap"/> is enabled. If <see langword="true"/>
  2495. /// any trailing spaces will be trimmed when either the <see cref="Text"/> property is changed or
  2496. /// when <see cref="Terminal.Gui.TextFormatter.WordWrap"/> is set to <see langword="true"/>.
  2497. /// The default is <see langword="false"/>.
  2498. /// </summary>
  2499. public virtual bool PreserveTrailingSpaces {
  2500. get => TextFormatter.PreserveTrailingSpaces;
  2501. set {
  2502. if (TextFormatter.PreserveTrailingSpaces != value) {
  2503. TextFormatter.PreserveTrailingSpaces = value;
  2504. TextFormatter.NeedsFormat = true;
  2505. }
  2506. }
  2507. }
  2508. /// <summary>
  2509. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  2510. /// </summary>
  2511. /// <value>The text alignment.</value>
  2512. public virtual TextAlignment TextAlignment {
  2513. get => TextFormatter.Alignment;
  2514. set {
  2515. TextFormatter.Alignment = value;
  2516. UpdateTextFormatterText ();
  2517. OnResizeNeeded ();
  2518. }
  2519. }
  2520. /// <summary>
  2521. /// Gets or sets how the View's <see cref="Text"/> is aligned vertically when drawn. Changing this property will redisplay the <see cref="View"/>.
  2522. /// </summary>
  2523. /// <value>The text alignment.</value>
  2524. public virtual VerticalTextAlignment VerticalTextAlignment {
  2525. get => TextFormatter.VerticalAlignment;
  2526. set {
  2527. TextFormatter.VerticalAlignment = value;
  2528. SetNeedsDisplay ();
  2529. }
  2530. }
  2531. /// <summary>
  2532. /// Gets or sets the direction of the View's <see cref="Text"/>. Changing this property will redisplay the <see cref="View"/>.
  2533. /// </summary>
  2534. /// <value>The text alignment.</value>
  2535. public virtual TextDirection TextDirection {
  2536. get => TextFormatter.Direction;
  2537. set {
  2538. if (!IsInitialized) {
  2539. TextFormatter.Direction = value;
  2540. } else {
  2541. UpdateTextDirection (value);
  2542. }
  2543. }
  2544. }
  2545. private void UpdateTextDirection (TextDirection newDirection)
  2546. {
  2547. var directionChanged = TextFormatter.IsHorizontalDirection (TextFormatter.Direction)
  2548. != TextFormatter.IsHorizontalDirection (newDirection);
  2549. TextFormatter.Direction = newDirection;
  2550. var isValidOldAutoSize = autoSize && IsValidAutoSize (out var _);
  2551. UpdateTextFormatterText ();
  2552. if ((!ForceValidatePosDim && directionChanged && AutoSize)
  2553. || (ForceValidatePosDim && directionChanged && AutoSize && isValidOldAutoSize)) {
  2554. OnResizeNeeded ();
  2555. } else if (directionChanged && IsAdded) {
  2556. SetWidthHeight (Bounds.Size);
  2557. SetMinWidthHeight ();
  2558. } else {
  2559. SetMinWidthHeight ();
  2560. }
  2561. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2562. SetNeedsDisplay ();
  2563. }
  2564. /// <summary>
  2565. /// Get or sets if the <see cref="View"/> has been initialized (via <see cref="ISupportInitialize.BeginInit"/>
  2566. /// and <see cref="ISupportInitialize.EndInit"/>).
  2567. /// </summary>
  2568. /// <para>
  2569. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification.IsInitialized"/>
  2570. /// can be implemented, in which case the <see cref="ISupportInitialize"/>
  2571. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  2572. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  2573. /// to override base class layout code optimally by doing so only on first run,
  2574. /// instead of on every run.
  2575. /// </para>
  2576. public virtual bool IsInitialized { get; set; }
  2577. /// <summary>
  2578. /// Gets information if the view was already added to the <see cref="SuperView"/>.
  2579. /// </summary>
  2580. public bool IsAdded { get; private set; }
  2581. bool oldEnabled;
  2582. /// <inheritdoc/>
  2583. public override bool Enabled {
  2584. get => base.Enabled;
  2585. set {
  2586. if (base.Enabled != value) {
  2587. if (value) {
  2588. if (SuperView == null || SuperView?.Enabled == true) {
  2589. base.Enabled = value;
  2590. }
  2591. } else {
  2592. base.Enabled = value;
  2593. }
  2594. if (!value && HasFocus) {
  2595. SetHasFocus (false, this);
  2596. }
  2597. OnEnabledChanged ();
  2598. SetNeedsDisplay ();
  2599. if (subviews != null) {
  2600. foreach (var view in subviews) {
  2601. if (!value) {
  2602. view.oldEnabled = view.Enabled;
  2603. view.Enabled = false;
  2604. } else {
  2605. view.Enabled = view.oldEnabled;
  2606. view.addingView = false;
  2607. }
  2608. }
  2609. }
  2610. }
  2611. }
  2612. }
  2613. /// <summary>
  2614. /// Gets or sets whether a view is cleared if the <see cref="Visible"/> property is <see langword="false"/>.
  2615. /// </summary>
  2616. public bool ClearOnVisibleFalse { get; set; } = true;
  2617. /// <inheritdoc/>>
  2618. public override bool Visible {
  2619. get => base.Visible;
  2620. set {
  2621. if (base.Visible != value) {
  2622. base.Visible = value;
  2623. if (!value) {
  2624. if (HasFocus) {
  2625. SetHasFocus (false, this);
  2626. }
  2627. if (ClearOnVisibleFalse) {
  2628. Clear ();
  2629. }
  2630. }
  2631. OnVisibleChanged ();
  2632. SetNeedsDisplay ();
  2633. }
  2634. }
  2635. }
  2636. // TODO: v2 Nuke teh Border property (rename BorderFrame to Border)
  2637. Border border;
  2638. /// <inheritdoc/>
  2639. public virtual Border Border {
  2640. get => border;
  2641. set {
  2642. if (border != value) {
  2643. border = value;
  2644. SetNeedsDisplay ();
  2645. if (border != null) {
  2646. Border_BorderChanged (border);
  2647. border.BorderChanged += Border_BorderChanged;
  2648. }
  2649. }
  2650. }
  2651. }
  2652. // TODO: v2 nuke This
  2653. /// <summary>
  2654. /// </summary>
  2655. public virtual bool IgnoreBorderPropertyOnRedraw { get; set; }
  2656. /// <summary>
  2657. /// Pretty prints the View
  2658. /// </summary>
  2659. /// <returns></returns>
  2660. public override string ToString ()
  2661. {
  2662. return $"{GetType ().Name}({Id})({Frame})";
  2663. }
  2664. void SetHotKey ()
  2665. {
  2666. if (TextFormatter == null) {
  2667. return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
  2668. }
  2669. TextFormatter.FindHotKey (text, HotKeySpecifier, true, out _, out var hk);
  2670. if (hotKey != hk) {
  2671. HotKey = hk;
  2672. }
  2673. }
  2674. bool ResizeView (bool autoSize)
  2675. {
  2676. if (!autoSize) {
  2677. return false;
  2678. }
  2679. var aSize = true;
  2680. var nBoundsSize = GetAutoSize ();
  2681. if (nBoundsSize != Bounds.Size) {
  2682. if (ForceValidatePosDim) {
  2683. aSize = SetWidthHeight (nBoundsSize);
  2684. } else {
  2685. Height = nBoundsSize.Height;
  2686. Width = nBoundsSize.Width; // = new Rect (Bounds.X, Bounds.Y, nBoundsSize.Width, nBoundsSize.Height);
  2687. }
  2688. }
  2689. // BUGBUG: This call may be redundant
  2690. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2691. return aSize;
  2692. }
  2693. /// <summary>
  2694. /// Resizes the View to fit the specified <see cref="Bounds"/> size.
  2695. /// </summary>
  2696. /// <param name="nBounds"></param>
  2697. /// <returns></returns>
  2698. bool SetWidthHeight (Size nBounds)
  2699. {
  2700. var aSize = false;
  2701. var canSizeW = TrySetWidth (nBounds.Width - GetHotKeySpecifierLength (), out var rW);
  2702. var canSizeH = TrySetHeight (nBounds.Height - GetHotKeySpecifierLength (false), out var rH);
  2703. if (canSizeW) {
  2704. aSize = true;
  2705. width = rW;
  2706. }
  2707. if (canSizeH) {
  2708. aSize = true;
  2709. height = rH;
  2710. }
  2711. if (aSize) {
  2712. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  2713. }
  2714. return aSize;
  2715. }
  2716. /// <summary>
  2717. /// Gets the dimensions required to fit <see cref="Text"/> using the text <see cref="Direction"/> specified by the
  2718. /// <see cref="TextFormatter"/> property and accounting for any <see cref="HotKeySpecifier"/> characters.
  2719. /// .
  2720. /// </summary>
  2721. /// <returns>The <see cref="Size"/> required to fit the text.</returns>
  2722. public Size GetAutoSize ()
  2723. {
  2724. var rect = TextFormatter.CalcRect (Bounds.X, Bounds.Y, TextFormatter.Text, TextFormatter.Direction);
  2725. return new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2726. rect.Size.Height - GetHotKeySpecifierLength (false));
  2727. }
  2728. bool IsValidAutoSize (out Size autoSize)
  2729. {
  2730. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2731. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2732. rect.Size.Height - GetHotKeySpecifierLength (false));
  2733. return !(ForceValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  2734. || frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  2735. || frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  2736. }
  2737. bool IsValidAutoSizeWidth (Dim width)
  2738. {
  2739. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2740. var dimValue = width.Anchor (0);
  2741. return !(ForceValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
  2742. - GetHotKeySpecifierLength ());
  2743. }
  2744. bool IsValidAutoSizeHeight (Dim height)
  2745. {
  2746. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2747. var dimValue = height.Anchor (0);
  2748. return !(ForceValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
  2749. - GetHotKeySpecifierLength (false));
  2750. }
  2751. /// <summary>
  2752. /// Gets the width or height of the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> characters
  2753. /// in the <see cref="Text"/> property.
  2754. /// </summary>
  2755. /// <remarks>
  2756. /// Only the first hotkey specifier found in <see cref="Text"/> is supported.
  2757. /// </remarks>
  2758. /// <param name="isWidth">If <see langword="true"/> (the default) the width required for the hotkey specifier is returned. Otherwise the height is returned.</param>
  2759. /// <returns>The number of characters required for the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>. If the text direction specified
  2760. /// by <see cref="TextDirection"/> does not match the <paramref name="isWidth"/> parameter, <c>0</c> is returned.</returns>
  2761. public int GetHotKeySpecifierLength (bool isWidth = true)
  2762. {
  2763. if (isWidth) {
  2764. return TextFormatter.IsHorizontalDirection (TextDirection) &&
  2765. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2766. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2767. } else {
  2768. return TextFormatter.IsVerticalDirection (TextDirection) &&
  2769. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2770. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2771. }
  2772. }
  2773. /// <summary>
  2774. /// Gets the dimensions required for <see cref="Text"/> ignoring a <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>.
  2775. /// </summary>
  2776. /// <returns></returns>
  2777. public Size GetSizeNeededForTextWithoutHotKey ()
  2778. {
  2779. return new Size (TextFormatter.Size.Width - GetHotKeySpecifierLength (),
  2780. TextFormatter.Size.Height - GetHotKeySpecifierLength (false));
  2781. }
  2782. /// <summary>
  2783. /// Gets the dimensions required for <see cref="Text"/> accounting for a <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> .
  2784. /// </summary>
  2785. /// <returns></returns>
  2786. public Size GetSizeNeededForTextAndHotKey ()
  2787. {
  2788. if (ustring.IsNullOrEmpty (TextFormatter.Text)) {
  2789. if (!IsInitialized) return Size.Empty;
  2790. return Bounds.Size;
  2791. }
  2792. // BUGBUG: This IGNORES what Text is set to, using on only the current View size. This doesn't seem to make sense.
  2793. // BUGBUG: This uses Frame; in v2 it should be Bounds
  2794. return new Size (frame.Size.Width + GetHotKeySpecifierLength (),
  2795. frame.Size.Height + GetHotKeySpecifierLength (false));
  2796. }
  2797. /// <inheritdoc/>
  2798. public override bool OnMouseEnter (MouseEvent mouseEvent)
  2799. {
  2800. if (!Enabled) {
  2801. return true;
  2802. }
  2803. if (!CanBeVisible (this)) {
  2804. return false;
  2805. }
  2806. var args = new MouseEventEventArgs (mouseEvent);
  2807. MouseEnter?.Invoke (this, args);
  2808. return args.Handled || base.OnMouseEnter (mouseEvent);
  2809. }
  2810. /// <inheritdoc/>
  2811. public override bool OnMouseLeave (MouseEvent mouseEvent)
  2812. {
  2813. if (!Enabled) {
  2814. return true;
  2815. }
  2816. if (!CanBeVisible (this)) {
  2817. return false;
  2818. }
  2819. var args = new MouseEventEventArgs (mouseEvent);
  2820. MouseLeave?.Invoke (this, args);
  2821. return args.Handled || base.OnMouseLeave (mouseEvent);
  2822. }
  2823. /// <summary>
  2824. /// Method invoked when a mouse event is generated
  2825. /// </summary>
  2826. /// <param name="mouseEvent"></param>
  2827. /// <returns><see langword="true"/>, if the event was handled, <see langword="false"/> otherwise.</returns>
  2828. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  2829. {
  2830. if (!Enabled) {
  2831. return true;
  2832. }
  2833. if (!CanBeVisible (this)) {
  2834. return false;
  2835. }
  2836. var args = new MouseEventEventArgs (mouseEvent);
  2837. if (OnMouseClick (args))
  2838. return true;
  2839. if (MouseEvent (mouseEvent))
  2840. return true;
  2841. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  2842. if (CanFocus && !HasFocus && SuperView != null) {
  2843. SuperView.SetFocus (this);
  2844. SetNeedsDisplay ();
  2845. }
  2846. return true;
  2847. }
  2848. return false;
  2849. }
  2850. /// <summary>
  2851. /// Invokes the MouseClick event.
  2852. /// </summary>
  2853. protected bool OnMouseClick (MouseEventEventArgs args)
  2854. {
  2855. if (!Enabled) {
  2856. return true;
  2857. }
  2858. MouseClick?.Invoke (this, args);
  2859. return args.Handled;
  2860. }
  2861. /// <inheritdoc/>
  2862. public override void OnCanFocusChanged () => CanFocusChanged?.Invoke (this, EventArgs.Empty);
  2863. /// <inheritdoc/>
  2864. public override void OnEnabledChanged () => EnabledChanged?.Invoke (this, EventArgs.Empty);
  2865. /// <inheritdoc/>
  2866. public override void OnVisibleChanged () => VisibleChanged?.Invoke (this, EventArgs.Empty);
  2867. /// <inheritdoc/>
  2868. protected override void Dispose (bool disposing)
  2869. {
  2870. Margin?.Dispose ();
  2871. Margin = null;
  2872. BorderFrame?.Dispose ();
  2873. Border = null;
  2874. Padding?.Dispose ();
  2875. Padding = null;
  2876. for (var i = InternalSubviews.Count - 1; i >= 0; i--) {
  2877. var subview = InternalSubviews [i];
  2878. Remove (subview);
  2879. subview.Dispose ();
  2880. }
  2881. base.Dispose (disposing);
  2882. }
  2883. /// <summary>
  2884. /// Signals the View that initialization is starting. See <see cref="ISupportInitialize"/>.
  2885. /// </summary>
  2886. /// <remarks>
  2887. /// <para>
  2888. /// Views can opt-in to more sophisticated initialization
  2889. /// by implementing overrides to <see cref="ISupportInitialize.BeginInit"/> and
  2890. /// <see cref="ISupportInitialize.EndInit"/> which will be called
  2891. /// when the view is added to a <see cref="SuperView"/>.
  2892. /// </para>
  2893. /// <para>
  2894. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification"/>
  2895. /// can be implemented too, in which case the <see cref="ISupportInitialize"/>
  2896. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  2897. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  2898. /// to override base class layout code optimally by doing so only on first run,
  2899. /// instead of on every run.
  2900. /// </para>
  2901. /// </remarks>
  2902. public virtual void BeginInit ()
  2903. {
  2904. if (!IsInitialized) {
  2905. oldCanFocus = CanFocus;
  2906. oldTabIndex = tabIndex;
  2907. UpdateTextDirection (TextDirection);
  2908. UpdateTextFormatterText ();
  2909. SetHotKey ();
  2910. // TODO: Figure out why ScrollView and other tests fail if this call is put here
  2911. // instead of the constructor.
  2912. OnResizeNeeded ();
  2913. //InitializeFrames ();
  2914. } else {
  2915. //throw new InvalidOperationException ("The view is already initialized.");
  2916. }
  2917. if (subviews?.Count > 0) {
  2918. foreach (var view in subviews) {
  2919. if (!view.IsInitialized) {
  2920. view.BeginInit ();
  2921. }
  2922. }
  2923. }
  2924. }
  2925. /// <summary>
  2926. /// Signals the View that initialization is ending. See <see cref="ISupportInitialize"/>.
  2927. /// </summary>
  2928. public void EndInit ()
  2929. {
  2930. IsInitialized = true;
  2931. if (subviews != null) {
  2932. foreach (var view in subviews) {
  2933. if (!view.IsInitialized) {
  2934. view.EndInit ();
  2935. }
  2936. }
  2937. }
  2938. Initialized?.Invoke (this, EventArgs.Empty);
  2939. }
  2940. bool CanBeVisible (View view)
  2941. {
  2942. if (!view.Visible) {
  2943. return false;
  2944. }
  2945. for (var c = view.SuperView; c != null; c = c.SuperView) {
  2946. if (!c.Visible) {
  2947. return false;
  2948. }
  2949. }
  2950. return true;
  2951. }
  2952. /// <summary>
  2953. /// Determines if the View's <see cref="Width"/> can be set to a new value.
  2954. /// </summary>
  2955. /// <param name="desiredWidth"></param>
  2956. /// <param name="resultWidth">Contains the width that would result if <see cref="Width"/> were set to <paramref name="desiredWidth"/>"/> </param>
  2957. /// <returns><see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False otherwise.</returns>
  2958. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  2959. {
  2960. var w = desiredWidth;
  2961. bool canSetWidth;
  2962. if (Width is Dim.DimCombine || Width is Dim.DimView || Width is Dim.DimFill) {
  2963. // It's a Dim.DimCombine and so can't be assigned. Let it have it's width anchored.
  2964. w = Width.Anchor (w);
  2965. canSetWidth = !ForceValidatePosDim;
  2966. } else if (Width is Dim.DimFactor factor) {
  2967. // Tries to get the SuperView width otherwise the view width.
  2968. var sw = SuperView != null ? SuperView.Frame.Width : w;
  2969. if (factor.IsFromRemaining ()) {
  2970. sw -= Frame.X;
  2971. }
  2972. w = Width.Anchor (sw);
  2973. canSetWidth = !ForceValidatePosDim;
  2974. } else {
  2975. canSetWidth = true;
  2976. }
  2977. resultWidth = w;
  2978. return canSetWidth;
  2979. }
  2980. /// <summary>
  2981. /// Determines if the View's <see cref="Height"/> can be set to a new value.
  2982. /// </summary>
  2983. /// <param name="desiredHeight"></param>
  2984. /// <param name="resultHeight">Contains the width that would result if <see cref="Height"/> were set to <paramref name="desiredHeight"/>"/> </param>
  2985. /// <returns><see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False otherwise.</returns>
  2986. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  2987. {
  2988. var h = desiredHeight;
  2989. bool canSetHeight;
  2990. switch (Height) {
  2991. case Dim.DimCombine _:
  2992. case Dim.DimView _:
  2993. case Dim.DimFill _:
  2994. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  2995. h = Height.Anchor (h);
  2996. canSetHeight = !ForceValidatePosDim;
  2997. break;
  2998. case Dim.DimFactor factor:
  2999. // Tries to get the SuperView height otherwise the view height.
  3000. var sh = SuperView != null ? SuperView.Frame.Height : h;
  3001. if (factor.IsFromRemaining ()) {
  3002. sh -= Frame.Y;
  3003. }
  3004. h = Height.Anchor (sh);
  3005. canSetHeight = !ForceValidatePosDim;
  3006. break;
  3007. default:
  3008. canSetHeight = true;
  3009. break;
  3010. }
  3011. resultHeight = h;
  3012. return canSetHeight;
  3013. }
  3014. /// <summary>
  3015. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3016. /// </summary>
  3017. /// <returns><see cref="Terminal.Gui.ColorScheme.Normal"/> if <see cref="Enabled"/> is <see langword="true"/>
  3018. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3019. /// If it's overridden can return other values.</returns>
  3020. public virtual Attribute GetNormalColor ()
  3021. {
  3022. return Enabled ? ColorScheme.Normal : ColorScheme.Disabled;
  3023. }
  3024. /// <summary>
  3025. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3026. /// </summary>
  3027. /// <returns><see cref="Terminal.Gui.ColorScheme.Focus"/> if <see cref="Enabled"/> is <see langword="true"/>
  3028. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3029. /// If it's overridden can return other values.</returns>
  3030. public virtual Attribute GetFocusColor ()
  3031. {
  3032. return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  3033. }
  3034. /// <summary>
  3035. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3036. /// </summary>
  3037. /// <returns><see cref="Terminal.Gui.ColorScheme.HotNormal"/> if <see cref="Enabled"/> is <see langword="true"/>
  3038. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3039. /// If it's overridden can return other values.</returns>
  3040. public virtual Attribute GetHotNormalColor ()
  3041. {
  3042. return Enabled ? ColorScheme.HotNormal : ColorScheme.Disabled;
  3043. }
  3044. /// <summary>
  3045. /// Get the top superview of a given <see cref="View"/>.
  3046. /// </summary>
  3047. /// <returns>The superview view.</returns>
  3048. public View GetTopSuperView (View view = null, View superview = null)
  3049. {
  3050. View top = superview ?? Application.Top;
  3051. for (var v = view?.SuperView ?? (this?.SuperView); v != null; v = v.SuperView) {
  3052. top = v;
  3053. if (top == superview) {
  3054. break;
  3055. }
  3056. }
  3057. return top;
  3058. }
  3059. }
  3060. }