View.cs 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533
  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)); // Set frame, not Frame!
  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)); // Set frame, not Frame!
  931. }
  932. //// BUGBUG: I think these calls are redundant or should be moved into just the AutoSize case
  933. if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
  934. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  935. LayoutFrames ();
  936. SetMinWidthHeight ();
  937. SetNeedsLayout ();
  938. SetNeedsDisplay ();
  939. }
  940. }
  941. void TextFormatter_HotKeyChanged (object sender, KeyChangedEventArgs e)
  942. {
  943. HotKeyChanged?.Invoke (this, e);
  944. }
  945. internal bool LayoutNeeded { get; private set; } = true;
  946. internal void SetNeedsLayout ()
  947. {
  948. if (LayoutNeeded)
  949. return;
  950. LayoutNeeded = true;
  951. if (SuperView == null)
  952. return;
  953. SuperView.SetNeedsLayout ();
  954. foreach (var view in Subviews) {
  955. view.SetNeedsLayout ();
  956. }
  957. TextFormatter.NeedsFormat = true;
  958. }
  959. /// <summary>
  960. /// Removes the <see cref="SetNeedsLayout"/> setting on this view.
  961. /// </summary>
  962. protected void ClearLayoutNeeded ()
  963. {
  964. LayoutNeeded = false;
  965. }
  966. // The view-relative region that needs to be redrawn
  967. internal Rect _needsDisplay { get; private set; } = Rect.Empty;
  968. /// <summary>
  969. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  970. /// </summary>
  971. public void SetNeedsDisplay ()
  972. {
  973. if (!IsInitialized) return;
  974. SetNeedsDisplay (Bounds);
  975. }
  976. /// <summary>
  977. /// Flags the view-relative region on this View as needing to be redrawn.
  978. /// </summary>
  979. /// <param name="region">The view-relative region that needs to be redrawn.</param>
  980. public void SetNeedsDisplay (Rect region)
  981. {
  982. if (_needsDisplay.IsEmpty)
  983. _needsDisplay = region;
  984. else {
  985. var x = Math.Min (_needsDisplay.X, region.X);
  986. var y = Math.Min (_needsDisplay.Y, region.Y);
  987. var w = Math.Max (_needsDisplay.Width, region.Width);
  988. var h = Math.Max (_needsDisplay.Height, region.Height);
  989. _needsDisplay = new Rect (x, y, w, h);
  990. }
  991. _superView?.SetSubViewNeedsDisplay ();
  992. if (subviews == null)
  993. return;
  994. foreach (var view in subviews)
  995. if (view.Frame.IntersectsWith (region)) {
  996. var childRegion = Rect.Intersect (view.Frame, region);
  997. childRegion.X -= view.Frame.X;
  998. childRegion.Y -= view.Frame.Y;
  999. view.SetNeedsDisplay (childRegion);
  1000. }
  1001. }
  1002. private Rect GetNeedsDisplayRectScreen (Rect containerBounds)
  1003. {
  1004. Rect rect = ViewToScreen (_needsDisplay);
  1005. if (!containerBounds.IsEmpty) {
  1006. rect.Width = Math.Min (_needsDisplay.Width, containerBounds.Width);
  1007. rect.Height = Math.Min (_needsDisplay.Height, containerBounds.Height);
  1008. }
  1009. return rect;
  1010. }
  1011. internal bool _childNeedsDisplay { get; private set; }
  1012. /// <summary>
  1013. /// Indicates that any Subviews (in the <see cref="Subviews"/> list) need to be repainted.
  1014. /// </summary>
  1015. public void SetSubViewNeedsDisplay ()
  1016. {
  1017. if (_childNeedsDisplay) {
  1018. return;
  1019. }
  1020. _childNeedsDisplay = true;
  1021. if (_superView != null && !_superView._childNeedsDisplay)
  1022. _superView.SetSubViewNeedsDisplay ();
  1023. }
  1024. internal bool addingView;
  1025. /// <summary>
  1026. /// Adds a subview (child) to this view.
  1027. /// </summary>
  1028. /// <remarks>
  1029. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property.
  1030. /// See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  1031. /// </remarks>
  1032. public virtual void Add (View view)
  1033. {
  1034. if (view == null) {
  1035. return;
  1036. }
  1037. if (subviews == null) {
  1038. subviews = new List<View> ();
  1039. }
  1040. if (tabIndexes == null) {
  1041. tabIndexes = new List<View> ();
  1042. }
  1043. subviews.Add (view);
  1044. tabIndexes.Add (view);
  1045. view._superView = this;
  1046. if (view.CanFocus) {
  1047. addingView = true;
  1048. if (SuperView?.CanFocus == false) {
  1049. SuperView.addingView = true;
  1050. SuperView.CanFocus = true;
  1051. SuperView.addingView = false;
  1052. }
  1053. CanFocus = true;
  1054. view.tabIndex = tabIndexes.IndexOf (view);
  1055. addingView = false;
  1056. }
  1057. if (view.Enabled && !Enabled) {
  1058. view.oldEnabled = true;
  1059. view.Enabled = false;
  1060. }
  1061. SetNeedsLayout ();
  1062. SetNeedsDisplay ();
  1063. OnAdded (new SuperViewChangedEventArgs (this, view));
  1064. if (IsInitialized && !view.IsInitialized) {
  1065. view.BeginInit ();
  1066. view.EndInit ();
  1067. }
  1068. }
  1069. /// <summary>
  1070. /// Adds the specified views (children) to the view.
  1071. /// </summary>
  1072. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  1073. /// <remarks>
  1074. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property.
  1075. /// See also <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  1076. /// </remarks>
  1077. public void Add (params View [] views)
  1078. {
  1079. if (views == null) {
  1080. return;
  1081. }
  1082. foreach (var view in views) {
  1083. Add (view);
  1084. }
  1085. }
  1086. /// <summary>
  1087. /// Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  1088. /// </summary>
  1089. public virtual void RemoveAll ()
  1090. {
  1091. if (subviews == null) {
  1092. return;
  1093. }
  1094. while (subviews.Count > 0) {
  1095. Remove (subviews [0]);
  1096. }
  1097. }
  1098. /// <summary>
  1099. /// Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.
  1100. /// </summary>
  1101. /// <remarks>
  1102. /// </remarks>
  1103. public virtual void Remove (View view)
  1104. {
  1105. if (view == null || subviews == null) return;
  1106. var touched = view.Frame;
  1107. subviews.Remove (view);
  1108. tabIndexes.Remove (view);
  1109. view._superView = null;
  1110. view.tabIndex = -1;
  1111. SetNeedsLayout ();
  1112. SetNeedsDisplay ();
  1113. foreach (var v in subviews) {
  1114. if (v.Frame.IntersectsWith (touched))
  1115. view.SetNeedsDisplay ();
  1116. }
  1117. OnRemoved (new SuperViewChangedEventArgs (this, view));
  1118. if (focused == view) {
  1119. focused = null;
  1120. }
  1121. }
  1122. void PerformActionForSubview (View subview, Action<View> action)
  1123. {
  1124. if (subviews.Contains (subview)) {
  1125. action (subview);
  1126. }
  1127. SetNeedsDisplay ();
  1128. subview.SetNeedsDisplay ();
  1129. }
  1130. /// <summary>
  1131. /// Brings the specified subview to the front so it is drawn on top of any other views.
  1132. /// </summary>
  1133. /// <param name="subview">The subview to send to the front</param>
  1134. /// <remarks>
  1135. /// <seealso cref="SendSubviewToBack"/>.
  1136. /// </remarks>
  1137. public void BringSubviewToFront (View subview)
  1138. {
  1139. PerformActionForSubview (subview, x => {
  1140. subviews.Remove (x);
  1141. subviews.Add (x);
  1142. });
  1143. }
  1144. /// <summary>
  1145. /// Sends the specified subview to the front so it is the first view drawn
  1146. /// </summary>
  1147. /// <param name="subview">The subview to send to the front</param>
  1148. /// <remarks>
  1149. /// <seealso cref="BringSubviewToFront(View)"/>.
  1150. /// </remarks>
  1151. public void SendSubviewToBack (View subview)
  1152. {
  1153. PerformActionForSubview (subview, x => {
  1154. subviews.Remove (x);
  1155. subviews.Insert (0, subview);
  1156. });
  1157. }
  1158. /// <summary>
  1159. /// Moves the subview backwards in the hierarchy, only one step
  1160. /// </summary>
  1161. /// <param name="subview">The subview to send backwards</param>
  1162. /// <remarks>
  1163. /// If you want to send the view all the way to the back use SendSubviewToBack.
  1164. /// </remarks>
  1165. public void SendSubviewBackwards (View subview)
  1166. {
  1167. PerformActionForSubview (subview, x => {
  1168. var idx = subviews.IndexOf (x);
  1169. if (idx > 0) {
  1170. subviews.Remove (x);
  1171. subviews.Insert (idx - 1, x);
  1172. }
  1173. });
  1174. }
  1175. /// <summary>
  1176. /// Moves the subview backwards in the hierarchy, only one step
  1177. /// </summary>
  1178. /// <param name="subview">The subview to send backwards</param>
  1179. /// <remarks>
  1180. /// If you want to send the view all the way to the back use SendSubviewToBack.
  1181. /// </remarks>
  1182. public void BringSubviewForward (View subview)
  1183. {
  1184. PerformActionForSubview (subview, x => {
  1185. var idx = subviews.IndexOf (x);
  1186. if (idx + 1 < subviews.Count) {
  1187. subviews.Remove (x);
  1188. subviews.Insert (idx + 1, x);
  1189. }
  1190. });
  1191. }
  1192. /// <summary>
  1193. /// Clears the view region with the current color.
  1194. /// </summary>
  1195. /// <remarks>
  1196. /// <para>
  1197. /// This clears the entire region used by this view.
  1198. /// </para>
  1199. /// </remarks>
  1200. public void Clear ()
  1201. {
  1202. var h = Frame.Height;
  1203. var w = Frame.Width;
  1204. for (var line = 0; line < h; line++) {
  1205. Move (0, line);
  1206. for (var col = 0; col < w; col++)
  1207. Driver.AddRune (' ');
  1208. }
  1209. }
  1210. // BUGBUG: Stupid that this takes screen-relative. We should have a tenet that says
  1211. // "View APIs only deal with View-relative coords".
  1212. /// <summary>
  1213. /// Clears the specified region with the current color.
  1214. /// </summary>
  1215. /// <remarks>
  1216. /// </remarks>
  1217. /// <param name="regionScreen">The screen-relative region to clear.</param>
  1218. public void Clear (Rect regionScreen)
  1219. {
  1220. var h = regionScreen.Height;
  1221. var w = regionScreen.Width;
  1222. for (var line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  1223. Driver.Move (regionScreen.X, line);
  1224. for (var col = 0; col < w; col++)
  1225. Driver.AddRune (' ');
  1226. }
  1227. }
  1228. /// <summary>
  1229. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  1230. /// </summary>
  1231. /// <returns>The mapped point.</returns>
  1232. /// <param name="x">X screen-coordinate point.</param>
  1233. /// <param name="y">Y screen-coordinate point.</param>
  1234. public Point ScreenToView (int x, int y)
  1235. {
  1236. if (SuperView == null) {
  1237. return new Point (x - Frame.X, y - frame.Y);
  1238. } else {
  1239. var parent = SuperView.ScreenToView (x, y);
  1240. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  1241. }
  1242. }
  1243. /// <summary>
  1244. /// Converts a point from screen-relative coordinates to bounds-relative coordinates.
  1245. /// </summary>
  1246. /// <returns>The mapped point.</returns>
  1247. /// <param name="x">X screen-coordinate point.</param>
  1248. /// <param name="y">Y screen-coordinate point.</param>
  1249. public Point ScreenToBounds (int x, int y)
  1250. {
  1251. if (SuperView == null) {
  1252. var boundsOffset = GetBoundsOffset ();
  1253. return new Point (x - Frame.X + boundsOffset.X, y - Frame.Y + boundsOffset.Y);
  1254. } else {
  1255. var parent = SuperView.ScreenToView (x, y);
  1256. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  1257. }
  1258. }
  1259. /// <summary>
  1260. /// Converts a view-relative location to a screen-relative location (col,row). The output is optionally clamped to the screen dimensions.
  1261. /// </summary>
  1262. /// <param name="col">View-relative column.</param>
  1263. /// <param name="row">View-relative row.</param>
  1264. /// <param name="rcol">Absolute column; screen-relative.</param>
  1265. /// <param name="rrow">Absolute row; screen-relative.</param>
  1266. /// <param name="clamped">If <see langword="true"/>, <paramref name="rcol"/> and <paramref name="rrow"/> will be clamped to the
  1267. /// screen dimensions (they never be negative and will always be less than to <see cref="ConsoleDriver.Cols"/> and
  1268. /// <see cref="ConsoleDriver.Rows"/>, respectively.</param>
  1269. public virtual void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clamped = true)
  1270. {
  1271. var boundsOffset = GetBoundsOffset ();
  1272. rcol = col + Frame.X + boundsOffset.X;
  1273. rrow = row + Frame.Y + boundsOffset.Y;
  1274. var super = SuperView;
  1275. while (super != null) {
  1276. boundsOffset = super.GetBoundsOffset ();
  1277. rcol += super.Frame.X + boundsOffset.X;
  1278. rrow += super.Frame.Y + boundsOffset.Y;
  1279. super = super.SuperView;
  1280. }
  1281. // The following ensures that the cursor is always in the screen boundaries.
  1282. if (clamped) {
  1283. rrow = Math.Min (rrow, Driver.Rows - 1);
  1284. rcol = Math.Min (rcol, Driver.Cols - 1);
  1285. }
  1286. }
  1287. /// <summary>
  1288. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  1289. /// </summary>
  1290. internal Rect ViewToScreen (Rect region)
  1291. {
  1292. ViewToScreen (region.X, region.Y, out var x, out var y, clamped: false);
  1293. return new Rect (x, y, region.Width, region.Height);
  1294. }
  1295. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  1296. internal Rect ScreenClip (Rect regionScreen)
  1297. {
  1298. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  1299. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  1300. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  1301. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  1302. return new Rect (x, y, w, h);
  1303. }
  1304. /// <summary>
  1305. /// Sets the <see cref="ConsoleDriver"/>'s clip region to <see cref="Bounds"/>.
  1306. /// </summary>
  1307. /// <returns>The current screen-relative clip region, which can be then re-applied by setting <see cref="ConsoleDriver.Clip"/>.</returns>
  1308. /// <remarks>
  1309. /// <para>
  1310. /// <see cref="Bounds"/> is View-relative.
  1311. /// </para>
  1312. /// <para>
  1313. /// If <see cref="ConsoleDriver.Clip"/> and <see cref="Bounds"/> do not intersect, the clip region will be set to <see cref="Rect.Empty"/>.
  1314. /// </para>
  1315. /// </remarks>
  1316. public Rect ClipToBounds ()
  1317. {
  1318. var clip = Bounds;
  1319. return SetClip (clip);
  1320. }
  1321. // BUGBUG: v2 - SetClip should return VIEW-relative so that it can be used to reset it; using Driver.Clip directly should not be necessary.
  1322. /// <summary>
  1323. /// Sets the clip region to the specified view-relative region.
  1324. /// </summary>
  1325. /// <returns>The current screen-relative clip region, which can be then re-applied by setting <see cref="ConsoleDriver.Clip"/>.</returns>
  1326. /// <param name="region">View-relative clip region.</param>
  1327. /// <remarks>
  1328. /// If <see cref="ConsoleDriver.Clip"/> and <paramref name="region"/> do not intersect, the clip region will be set to <see cref="Rect.Empty"/>.
  1329. /// </remarks>
  1330. public Rect SetClip (Rect region)
  1331. {
  1332. var previous = Driver.Clip;
  1333. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  1334. return previous;
  1335. }
  1336. /// <summary>
  1337. /// Draws a frame in the current view, clipped by the boundary of this view
  1338. /// </summary>
  1339. /// <param name="region">View-relative region for the frame to be drawn.</param>
  1340. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  1341. /// <param name="fill">If set to <see langword="true"/> it fill will the contents.</param>
  1342. [ObsoleteAttribute ("This method is obsolete in v2. Use use LineCanvas or Frame instead.", false)]
  1343. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  1344. {
  1345. var scrRect = ViewToScreen (region);
  1346. var savedClip = ClipToBounds ();
  1347. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  1348. Driver.Clip = savedClip;
  1349. }
  1350. /// <summary>
  1351. /// Utility function to draw strings that contain a hotkey.
  1352. /// </summary>
  1353. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  1354. /// <param name="hotColor">Hot color.</param>
  1355. /// <param name="normalColor">Normal color.</param>
  1356. /// <remarks>
  1357. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  1358. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  1359. /// </remarks>
  1360. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  1361. {
  1362. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  1363. Application.Driver.SetAttribute (normalColor);
  1364. foreach (var rune in text) {
  1365. if (rune == hotkeySpec) {
  1366. Application.Driver.SetAttribute (hotColor);
  1367. continue;
  1368. }
  1369. Application.Driver.AddRune (rune);
  1370. Application.Driver.SetAttribute (normalColor);
  1371. }
  1372. }
  1373. /// <summary>
  1374. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  1375. /// </summary>
  1376. /// <param name="text">String to display, the underscore before a letter flags the next letter as the hotkey.</param>
  1377. /// <param name="focused">If set to <see langword="true"/> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  1378. /// <param name="scheme">The color scheme to use.</param>
  1379. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  1380. {
  1381. if (focused)
  1382. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  1383. else
  1384. DrawHotString (text, Enabled ? scheme.HotNormal : scheme.Disabled, Enabled ? scheme.Normal : scheme.Disabled);
  1385. }
  1386. /// <summary>
  1387. /// This moves the cursor to the specified column and row in the view.
  1388. /// </summary>
  1389. /// <returns>The move.</returns>
  1390. /// <param name="col">The column to move to, in view-relative coordinates.</param>
  1391. /// <param name="row">the row to move to, in view-relative coordinates.</param>
  1392. /// <param name="clipped">Whether to clip the result of the ViewToScreen method,
  1393. /// If <see langword="true"/>, the <paramref name="col"/> and <paramref name="row"/> values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).</param>
  1394. public void Move (int col, int row, bool clipped = true)
  1395. {
  1396. if (Driver.Rows == 0) {
  1397. return;
  1398. }
  1399. ViewToScreen (col, row, out var rCol, out var rRow, clipped);
  1400. Driver.Move (rCol, rRow);
  1401. }
  1402. /// <summary>
  1403. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1404. /// </summary>
  1405. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1406. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1407. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1408. /// the last focused view. Views should make sure that they place the cursor
  1409. /// in a visually sensible place.
  1410. public virtual void PositionCursor ()
  1411. {
  1412. if (!CanBeVisible (this) || !Enabled) {
  1413. return;
  1414. }
  1415. // BUGBUG: v2 - This needs to support children of Frames too
  1416. if (focused == null && SuperView != null) {
  1417. SuperView.EnsureFocus ();
  1418. } else if (focused?.Visible == true && focused?.Enabled == true && focused?.Frame.Width > 0 && focused.Frame.Height > 0) {
  1419. focused.PositionCursor ();
  1420. } else if (focused?.Visible == true && focused?.Enabled == false) {
  1421. focused = null;
  1422. } else if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
  1423. Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
  1424. } else {
  1425. Move (frame.X, frame.Y);
  1426. }
  1427. }
  1428. // BUGBUG: v2 - Seems weird that this is in View and not Responder.
  1429. bool _hasFocus;
  1430. /// <inheritdoc/>
  1431. public override bool HasFocus => _hasFocus;
  1432. void SetHasFocus (bool value, View view, bool force = false)
  1433. {
  1434. if (_hasFocus != value || force) {
  1435. _hasFocus = value;
  1436. if (value) {
  1437. OnEnter (view);
  1438. } else {
  1439. OnLeave (view);
  1440. }
  1441. SetNeedsDisplay ();
  1442. }
  1443. // Remove focus down the chain of subviews if focus is removed
  1444. if (!value && focused != null) {
  1445. var f = focused;
  1446. f.OnLeave (view);
  1447. f.SetHasFocus (false, view);
  1448. focused = null;
  1449. }
  1450. }
  1451. /// <summary>
  1452. /// Method invoked when a subview is being added to this view.
  1453. /// </summary>
  1454. /// <param name="e">Event where <see cref="ViewEventArgs.View"/> is the subview being added.</param>
  1455. public virtual void OnAdded (SuperViewChangedEventArgs e)
  1456. {
  1457. var view = e.Child;
  1458. view.IsAdded = true;
  1459. view.x ??= view.frame.X;
  1460. view.y ??= view.frame.Y;
  1461. view.width ??= view.frame.Width;
  1462. view.height ??= view.frame.Height;
  1463. view.Added?.Invoke (this, e);
  1464. }
  1465. /// <summary>
  1466. /// Method invoked when a subview is being removed from this view.
  1467. /// </summary>
  1468. /// <param name="e">Event args describing the subview being removed.</param>
  1469. public virtual void OnRemoved (SuperViewChangedEventArgs e)
  1470. {
  1471. var view = e.Child;
  1472. view.IsAdded = false;
  1473. view.Removed?.Invoke (this, e);
  1474. }
  1475. /// <inheritdoc/>
  1476. public override bool OnEnter (View view)
  1477. {
  1478. var args = new FocusEventArgs (view);
  1479. Enter?.Invoke (this, args);
  1480. if (args.Handled)
  1481. return true;
  1482. if (base.OnEnter (view))
  1483. return true;
  1484. return false;
  1485. }
  1486. /// <inheritdoc/>
  1487. public override bool OnLeave (View view)
  1488. {
  1489. var args = new FocusEventArgs (view);
  1490. Leave?.Invoke (this, args);
  1491. if (args.Handled)
  1492. return true;
  1493. if (base.OnLeave (view))
  1494. return true;
  1495. return false;
  1496. }
  1497. /// <summary>
  1498. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1499. /// </summary>
  1500. /// <value>The focused.</value>
  1501. public View Focused => focused;
  1502. /// <summary>
  1503. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1504. /// </summary>
  1505. /// <value>The most focused View.</value>
  1506. public View MostFocused {
  1507. get {
  1508. if (Focused == null)
  1509. return null;
  1510. var most = Focused.MostFocused;
  1511. if (most != null)
  1512. return most;
  1513. return Focused;
  1514. }
  1515. }
  1516. ColorScheme colorScheme;
  1517. /// <summary>
  1518. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1519. /// color scheme.
  1520. /// </summary>
  1521. public virtual ColorScheme ColorScheme {
  1522. get {
  1523. if (colorScheme == null) {
  1524. return SuperView?.ColorScheme;
  1525. }
  1526. return colorScheme;
  1527. }
  1528. set {
  1529. if (colorScheme != value) {
  1530. colorScheme = value;
  1531. SetNeedsDisplay ();
  1532. }
  1533. }
  1534. }
  1535. /// <summary>
  1536. /// Displays the specified character in the specified column and row of the View.
  1537. /// </summary>
  1538. /// <param name="col">Column (view-relative).</param>
  1539. /// <param name="row">Row (view-relative).</param>
  1540. /// <param name="ch">Ch.</param>
  1541. public void AddRune (int col, int row, Rune ch)
  1542. {
  1543. if (row < 0 || col < 0)
  1544. return;
  1545. if (row > frame.Height - 1 || col > frame.Width - 1)
  1546. return;
  1547. Move (col, row);
  1548. Driver.AddRune (ch);
  1549. }
  1550. /// <summary>
  1551. /// Removes the <see cref="_needsDisplay"/> and the <see cref="_childNeedsDisplay"/> setting on this view.
  1552. /// </summary>
  1553. protected void ClearNeedsDisplay ()
  1554. {
  1555. _needsDisplay = Rect.Empty;
  1556. _childNeedsDisplay = false;
  1557. }
  1558. // TODO: Make this cancelable
  1559. /// <summary>
  1560. ///
  1561. /// </summary>
  1562. /// <returns></returns>
  1563. public virtual bool OnDrawFrames (Rect bounds)
  1564. {
  1565. var prevClip = Driver.Clip;
  1566. if (SuperView != null) {
  1567. Driver.Clip = SuperView.ClipToBounds ();
  1568. }
  1569. Margin?.Redraw (Margin.Frame);
  1570. BorderFrame?.Redraw (BorderFrame.Frame);
  1571. Padding?.Redraw (Padding.Frame);
  1572. Driver.Clip = prevClip;
  1573. return true;
  1574. }
  1575. /// <summary>
  1576. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1577. /// </summary>
  1578. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1579. /// <remarks>
  1580. /// <para>
  1581. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1582. /// </para>
  1583. /// <para>
  1584. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1585. /// the last color that was set globally on the driver.
  1586. /// </para>
  1587. /// <para>
  1588. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1589. /// larger than the <ref name="bounds"/> parameter, as this will cause the driver to clip the entire region.
  1590. /// </para>
  1591. /// </remarks>
  1592. public virtual void Redraw (Rect bounds)
  1593. {
  1594. if (!CanBeVisible (this)) {
  1595. return;
  1596. }
  1597. OnDrawFrames (Frame);
  1598. var prevClip = ClipToBounds ();
  1599. // TODO: Implement complete event
  1600. // OnDrawFramesComplete (Frame)
  1601. if (ColorScheme != null) {
  1602. //Driver.SetAttribute (HasFocus ? GetFocusColor () : GetNormalColor ());
  1603. Driver.SetAttribute (GetNormalColor ());
  1604. }
  1605. Clear (ViewToScreen (bounds));
  1606. // Invoke DrawContentEvent
  1607. OnDrawContent (bounds);
  1608. // Draw subviews
  1609. // TODO: Implement OnDrawSubviews (cancelable);
  1610. if (subviews != null) {
  1611. foreach (var view in subviews) {
  1612. if (view.Visible) { //!view._needsDisplay.IsEmpty || view._childNeedsDisplay || view.LayoutNeeded) {
  1613. if (true) { //view.Frame.IntersectsWith (bounds)) { // && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1614. if (view.LayoutNeeded) {
  1615. view.LayoutSubviews ();
  1616. }
  1617. // Draw the subview
  1618. // Use the view's bounds (view-relative; Location will always be (0,0)
  1619. //if (view.Visible && view.Frame.Width > 0 && view.Frame.Height > 0) {
  1620. view.Redraw (view.Bounds);
  1621. //}
  1622. }
  1623. view.ClearNeedsDisplay ();
  1624. }
  1625. }
  1626. }
  1627. // Invoke DrawContentCompleteEvent
  1628. OnDrawContentComplete (bounds);
  1629. // BUGBUG: v2 - We should be able to use View.SetClip here and not have to resort to knowing Driver details.
  1630. Driver.Clip = prevClip;
  1631. ClearLayoutNeeded ();
  1632. ClearNeedsDisplay ();
  1633. }
  1634. /// <summary>
  1635. /// Event invoked when the content area of the View is to be drawn.
  1636. /// </summary>
  1637. /// <remarks>
  1638. /// <para>
  1639. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1640. /// </para>
  1641. /// <para>
  1642. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1643. /// </para>
  1644. /// </remarks>
  1645. public event EventHandler<DrawEventArgs> DrawContent;
  1646. /// <summary>
  1647. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1648. /// </summary>
  1649. /// <param name="contentArea">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1650. /// <remarks>
  1651. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1652. /// </remarks>
  1653. public virtual void OnDrawContent (Rect contentArea)
  1654. {
  1655. // TODO: Make DrawContent a cancelable event
  1656. // if (!DrawContent?.Invoke(this, new DrawEventArgs (viewport)) {
  1657. DrawContent?.Invoke (this, new DrawEventArgs (contentArea));
  1658. if (!ustring.IsNullOrEmpty (TextFormatter.Text)) {
  1659. if (TextFormatter != null) {
  1660. TextFormatter.NeedsFormat = true;
  1661. }
  1662. TextFormatter?.Draw (ViewToScreen (contentArea), HasFocus ? GetFocusColor () : GetNormalColor (),
  1663. HasFocus ? ColorScheme.HotFocus : GetHotNormalColor (),
  1664. new Rect (ViewToScreen (contentArea).Location, Bounds.Size), true);
  1665. SetSubViewNeedsDisplay ();
  1666. }
  1667. }
  1668. /// <summary>
  1669. /// Event invoked when the content area of the View is completed drawing.
  1670. /// </summary>
  1671. /// <remarks>
  1672. /// <para>
  1673. /// Will be invoked after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1674. /// </para>
  1675. /// <para>
  1676. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1677. /// </para>
  1678. /// </remarks>
  1679. public event EventHandler<DrawEventArgs> DrawContentComplete;
  1680. /// <summary>
  1681. /// Enables overrides after completed drawing infinitely scrolled content and/or a background behind removed controls.
  1682. /// </summary>
  1683. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1684. /// <remarks>
  1685. /// This method will be called after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1686. /// </remarks>
  1687. public virtual void OnDrawContentComplete (Rect viewport)
  1688. {
  1689. DrawContentComplete?.Invoke (this, new DrawEventArgs (viewport));
  1690. }
  1691. /// <summary>
  1692. /// Causes the specified subview to have focus.
  1693. /// </summary>
  1694. /// <param name="view">View.</param>
  1695. void SetFocus (View view)
  1696. {
  1697. if (view == null) {
  1698. return;
  1699. }
  1700. //Console.WriteLine ($"Request to focus {view}");
  1701. if (!view.CanFocus || !view.Visible || !view.Enabled) {
  1702. return;
  1703. }
  1704. if (focused?._hasFocus == true && focused == view) {
  1705. return;
  1706. }
  1707. if ((focused?._hasFocus == true && focused?.SuperView == view) || view == this) {
  1708. if (!view._hasFocus) {
  1709. view._hasFocus = true;
  1710. }
  1711. return;
  1712. }
  1713. // Make sure that this view is a subview
  1714. View c;
  1715. for (c = view._superView; c != null; c = c._superView)
  1716. if (c == this)
  1717. break;
  1718. if (c == null)
  1719. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1720. if (focused != null)
  1721. focused.SetHasFocus (false, view);
  1722. var f = focused;
  1723. focused = view;
  1724. focused.SetHasFocus (true, f);
  1725. focused.EnsureFocus ();
  1726. // Send focus upwards
  1727. if (SuperView != null) {
  1728. SuperView.SetFocus (this);
  1729. } else {
  1730. SetFocus (this);
  1731. }
  1732. }
  1733. /// <summary>
  1734. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  1735. /// </summary>
  1736. public void SetFocus ()
  1737. {
  1738. if (!CanBeVisible (this) || !Enabled) {
  1739. if (HasFocus) {
  1740. SetHasFocus (false, this);
  1741. }
  1742. return;
  1743. }
  1744. if (SuperView != null) {
  1745. SuperView.SetFocus (this);
  1746. } else {
  1747. SetFocus (this);
  1748. }
  1749. }
  1750. /// <summary>
  1751. /// Invoked when a character key is pressed and occurs after the key up event.
  1752. /// </summary>
  1753. public event EventHandler<KeyEventEventArgs> KeyPress;
  1754. /// <inheritdoc/>
  1755. public override bool ProcessKey (KeyEvent keyEvent)
  1756. {
  1757. if (!Enabled) {
  1758. return false;
  1759. }
  1760. var args = new KeyEventEventArgs (keyEvent);
  1761. KeyPress?.Invoke (this, args);
  1762. if (args.Handled)
  1763. return true;
  1764. if (Focused?.Enabled == true) {
  1765. Focused?.KeyPress?.Invoke (this, args);
  1766. if (args.Handled)
  1767. return true;
  1768. }
  1769. return Focused?.Enabled == true && Focused?.ProcessKey (keyEvent) == true;
  1770. }
  1771. /// <summary>
  1772. /// Invokes any binding that is registered on this <see cref="View"/>
  1773. /// and matches the <paramref name="keyEvent"/>
  1774. /// </summary>
  1775. /// <param name="keyEvent">The key event passed.</param>
  1776. protected bool? InvokeKeybindings (KeyEvent keyEvent)
  1777. {
  1778. bool? toReturn = null;
  1779. if (KeyBindings.ContainsKey (keyEvent.Key)) {
  1780. foreach (var command in KeyBindings [keyEvent.Key]) {
  1781. if (!CommandImplementations.ContainsKey (command)) {
  1782. 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})");
  1783. }
  1784. // each command has its own return value
  1785. var thisReturn = CommandImplementations [command] ();
  1786. // if we haven't got anything yet, the current command result should be used
  1787. if (toReturn == null) {
  1788. toReturn = thisReturn;
  1789. }
  1790. // if ever see a true then that's what we will return
  1791. if (thisReturn ?? false) {
  1792. toReturn = true;
  1793. }
  1794. }
  1795. }
  1796. return toReturn;
  1797. }
  1798. /// <summary>
  1799. /// <para>Adds a new key combination that will trigger the given <paramref name="command"/>
  1800. /// (if supported by the View - see <see cref="GetSupportedCommands"/>)
  1801. /// </para>
  1802. /// <para>If the key is already bound to a different <see cref="Command"/> it will be
  1803. /// rebound to this one</para>
  1804. /// <remarks>Commands are only ever applied to the current <see cref="View"/>(i.e. this feature
  1805. /// cannot be used to switch focus to another view and perform multiple commands there) </remarks>
  1806. /// </summary>
  1807. /// <param name="key"></param>
  1808. /// <param name="command">The command(s) to run on the <see cref="View"/> when <paramref name="key"/> is pressed.
  1809. /// When specifying multiple commands, all commands will be applied in sequence. The bound <paramref name="key"/> strike
  1810. /// will be consumed if any took effect.</param>
  1811. public void AddKeyBinding (Key key, params Command [] command)
  1812. {
  1813. if (command.Length == 0) {
  1814. throw new ArgumentException ("At least one command must be specified", nameof (command));
  1815. }
  1816. if (KeyBindings.ContainsKey (key)) {
  1817. KeyBindings [key] = command;
  1818. } else {
  1819. KeyBindings.Add (key, command);
  1820. }
  1821. }
  1822. /// <summary>
  1823. /// Replaces a key combination already bound to <see cref="Command"/>.
  1824. /// </summary>
  1825. /// <param name="fromKey">The key to be replaced.</param>
  1826. /// <param name="toKey">The new key to be used.</param>
  1827. protected void ReplaceKeyBinding (Key fromKey, Key toKey)
  1828. {
  1829. if (KeyBindings.ContainsKey (fromKey)) {
  1830. var value = KeyBindings [fromKey];
  1831. KeyBindings.Remove (fromKey);
  1832. KeyBindings [toKey] = value;
  1833. }
  1834. }
  1835. /// <summary>
  1836. /// Checks if the key binding already exists.
  1837. /// </summary>
  1838. /// <param name="key">The key to check.</param>
  1839. /// <returns><see langword="true"/> If the key already exist, <see langword="false"/> otherwise.</returns>
  1840. public bool ContainsKeyBinding (Key key)
  1841. {
  1842. return KeyBindings.ContainsKey (key);
  1843. }
  1844. /// <summary>
  1845. /// Removes all bound keys from the View and resets the default bindings.
  1846. /// </summary>
  1847. public void ClearKeybindings ()
  1848. {
  1849. KeyBindings.Clear ();
  1850. }
  1851. /// <summary>
  1852. /// Clears the existing keybinding (if any) for the given <paramref name="key"/>.
  1853. /// </summary>
  1854. /// <param name="key"></param>
  1855. public void ClearKeybinding (Key key)
  1856. {
  1857. KeyBindings.Remove (key);
  1858. }
  1859. /// <summary>
  1860. /// Removes all key bindings that trigger the given command. Views can have multiple different
  1861. /// keys bound to the same command and this method will clear all of them.
  1862. /// </summary>
  1863. /// <param name="command"></param>
  1864. public void ClearKeybinding (params Command [] command)
  1865. {
  1866. foreach (var kvp in KeyBindings.Where (kvp => kvp.Value.SequenceEqual (command)).ToArray ()) {
  1867. KeyBindings.Remove (kvp.Key);
  1868. }
  1869. }
  1870. /// <summary>
  1871. /// <para>States that the given <see cref="View"/> supports a given <paramref name="command"/>
  1872. /// and what <paramref name="f"/> to perform to make that command happen
  1873. /// </para>
  1874. /// <para>If the <paramref name="command"/> already has an implementation the <paramref name="f"/>
  1875. /// will replace the old one</para>
  1876. /// </summary>
  1877. /// <param name="command">The command.</param>
  1878. /// <param name="f">The function.</param>
  1879. protected void AddCommand (Command command, Func<bool?> f)
  1880. {
  1881. // if there is already an implementation of this command
  1882. if (CommandImplementations.ContainsKey (command)) {
  1883. // replace that implementation
  1884. CommandImplementations [command] = f;
  1885. } else {
  1886. // else record how to perform the action (this should be the normal case)
  1887. CommandImplementations.Add (command, f);
  1888. }
  1889. }
  1890. /// <summary>
  1891. /// Returns all commands that are supported by this <see cref="View"/>.
  1892. /// </summary>
  1893. /// <returns></returns>
  1894. public IEnumerable<Command> GetSupportedCommands ()
  1895. {
  1896. return CommandImplementations.Keys;
  1897. }
  1898. /// <summary>
  1899. /// Gets the key used by a command.
  1900. /// </summary>
  1901. /// <param name="command">The command to search.</param>
  1902. /// <returns>The <see cref="Key"/> used by a <see cref="Command"/></returns>
  1903. public Key GetKeyFromCommand (params Command [] command)
  1904. {
  1905. return KeyBindings.First (kb => kb.Value.SequenceEqual (command)).Key;
  1906. }
  1907. /// <inheritdoc/>
  1908. public override bool ProcessHotKey (KeyEvent keyEvent)
  1909. {
  1910. if (!Enabled) {
  1911. return false;
  1912. }
  1913. var args = new KeyEventEventArgs (keyEvent);
  1914. if (MostFocused?.Enabled == true) {
  1915. MostFocused?.KeyPress?.Invoke (this, args);
  1916. if (args.Handled)
  1917. return true;
  1918. }
  1919. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1920. return true;
  1921. if (subviews == null || subviews.Count == 0)
  1922. return false;
  1923. foreach (var view in subviews)
  1924. if (view.Enabled && view.ProcessHotKey (keyEvent))
  1925. return true;
  1926. return false;
  1927. }
  1928. /// <inheritdoc/>
  1929. public override bool ProcessColdKey (KeyEvent keyEvent)
  1930. {
  1931. if (!Enabled) {
  1932. return false;
  1933. }
  1934. var args = new KeyEventEventArgs (keyEvent);
  1935. KeyPress?.Invoke (this, args);
  1936. if (args.Handled)
  1937. return true;
  1938. if (MostFocused?.Enabled == true) {
  1939. MostFocused?.KeyPress?.Invoke (this, args);
  1940. if (args.Handled)
  1941. return true;
  1942. }
  1943. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1944. return true;
  1945. if (subviews == null || subviews.Count == 0)
  1946. return false;
  1947. foreach (var view in subviews)
  1948. if (view.Enabled && view.ProcessColdKey (keyEvent))
  1949. return true;
  1950. return false;
  1951. }
  1952. /// <summary>
  1953. /// Invoked when a key is pressed.
  1954. /// </summary>
  1955. public event EventHandler<KeyEventEventArgs> KeyDown;
  1956. /// <inheritdoc/>
  1957. public override bool OnKeyDown (KeyEvent keyEvent)
  1958. {
  1959. if (!Enabled) {
  1960. return false;
  1961. }
  1962. var args = new KeyEventEventArgs (keyEvent);
  1963. KeyDown?.Invoke (this, args);
  1964. if (args.Handled) {
  1965. return true;
  1966. }
  1967. if (Focused?.Enabled == true) {
  1968. Focused.KeyDown?.Invoke (this, args);
  1969. if (args.Handled) {
  1970. return true;
  1971. }
  1972. if (Focused?.OnKeyDown (keyEvent) == true) {
  1973. return true;
  1974. }
  1975. }
  1976. return false;
  1977. }
  1978. /// <summary>
  1979. /// Invoked when a key is released.
  1980. /// </summary>
  1981. public event EventHandler<KeyEventEventArgs> KeyUp;
  1982. /// <inheritdoc/>
  1983. public override bool OnKeyUp (KeyEvent keyEvent)
  1984. {
  1985. if (!Enabled) {
  1986. return false;
  1987. }
  1988. var args = new KeyEventEventArgs (keyEvent);
  1989. KeyUp?.Invoke (this, args);
  1990. if (args.Handled) {
  1991. return true;
  1992. }
  1993. if (Focused?.Enabled == true) {
  1994. Focused.KeyUp?.Invoke (this, args);
  1995. if (args.Handled) {
  1996. return true;
  1997. }
  1998. if (Focused?.OnKeyUp (keyEvent) == true) {
  1999. return true;
  2000. }
  2001. }
  2002. return false;
  2003. }
  2004. /// <summary>
  2005. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, does nothing.
  2006. /// </summary>
  2007. public void EnsureFocus ()
  2008. {
  2009. if (focused == null && subviews?.Count > 0) {
  2010. if (FocusDirection == Direction.Forward) {
  2011. FocusFirst ();
  2012. } else {
  2013. FocusLast ();
  2014. }
  2015. }
  2016. }
  2017. /// <summary>
  2018. /// Focuses the first focusable subview if one exists.
  2019. /// </summary>
  2020. public void FocusFirst ()
  2021. {
  2022. if (!CanBeVisible (this)) {
  2023. return;
  2024. }
  2025. if (tabIndexes == null) {
  2026. SuperView?.SetFocus (this);
  2027. return;
  2028. }
  2029. foreach (var view in tabIndexes) {
  2030. if (view.CanFocus && view.tabStop && view.Visible && view.Enabled) {
  2031. SetFocus (view);
  2032. return;
  2033. }
  2034. }
  2035. }
  2036. /// <summary>
  2037. /// Focuses the last focusable subview if one exists.
  2038. /// </summary>
  2039. public void FocusLast ()
  2040. {
  2041. if (!CanBeVisible (this)) {
  2042. return;
  2043. }
  2044. if (tabIndexes == null) {
  2045. SuperView?.SetFocus (this);
  2046. return;
  2047. }
  2048. for (var i = tabIndexes.Count; i > 0;) {
  2049. i--;
  2050. var v = tabIndexes [i];
  2051. if (v.CanFocus && v.tabStop && v.Visible && v.Enabled) {
  2052. SetFocus (v);
  2053. return;
  2054. }
  2055. }
  2056. }
  2057. /// <summary>
  2058. /// Focuses the previous view.
  2059. /// </summary>
  2060. /// <returns><see langword="true"/> if previous was focused, <see langword="false"/> otherwise.</returns>
  2061. public bool FocusPrev ()
  2062. {
  2063. if (!CanBeVisible (this)) {
  2064. return false;
  2065. }
  2066. FocusDirection = Direction.Backward;
  2067. if (tabIndexes == null || tabIndexes.Count == 0)
  2068. return false;
  2069. if (focused == null) {
  2070. FocusLast ();
  2071. return focused != null;
  2072. }
  2073. var focusedIdx = -1;
  2074. for (var i = tabIndexes.Count; i > 0;) {
  2075. i--;
  2076. var w = tabIndexes [i];
  2077. if (w.HasFocus) {
  2078. if (w.FocusPrev ())
  2079. return true;
  2080. focusedIdx = i;
  2081. continue;
  2082. }
  2083. if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
  2084. focused.SetHasFocus (false, w);
  2085. if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  2086. w.FocusLast ();
  2087. SetFocus (w);
  2088. return true;
  2089. }
  2090. }
  2091. if (focused != null) {
  2092. focused.SetHasFocus (false, this);
  2093. focused = null;
  2094. }
  2095. return false;
  2096. }
  2097. /// <summary>
  2098. /// Focuses the next view.
  2099. /// </summary>
  2100. /// <returns><see langword="true"/> if next was focused, <see langword="false"/> otherwise.</returns>
  2101. public bool FocusNext ()
  2102. {
  2103. if (!CanBeVisible (this)) {
  2104. return false;
  2105. }
  2106. FocusDirection = Direction.Forward;
  2107. if (tabIndexes == null || tabIndexes.Count == 0)
  2108. return false;
  2109. if (focused == null) {
  2110. FocusFirst ();
  2111. return focused != null;
  2112. }
  2113. var focusedIdx = -1;
  2114. for (var i = 0; i < tabIndexes.Count; i++) {
  2115. var w = tabIndexes [i];
  2116. if (w.HasFocus) {
  2117. if (w.FocusNext ())
  2118. return true;
  2119. focusedIdx = i;
  2120. continue;
  2121. }
  2122. if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
  2123. focused.SetHasFocus (false, w);
  2124. if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  2125. w.FocusFirst ();
  2126. SetFocus (w);
  2127. return true;
  2128. }
  2129. }
  2130. if (focused != null) {
  2131. focused.SetHasFocus (false, this);
  2132. focused = null;
  2133. }
  2134. return false;
  2135. }
  2136. View GetMostFocused (View view)
  2137. {
  2138. if (view == null) {
  2139. return null;
  2140. }
  2141. return view.focused != null ? GetMostFocused (view.focused) : view;
  2142. }
  2143. /// <summary>
  2144. /// Sets the View's <see cref="Frame"/> to the frame-relative coordinates if its container. The
  2145. /// container size and location are specified by <paramref name="superviewFrame"/> and are relative to the
  2146. /// View's superview.
  2147. /// </summary>
  2148. /// <param name="superviewFrame">The supserview-relative rectangle describing View's container (nominally the
  2149. /// same as <c>this.SuperView.Frame</c>).</param>
  2150. internal void SetRelativeLayout (Rect superviewFrame)
  2151. {
  2152. int newX, newW, newY, newH;
  2153. var autosize = Size.Empty;
  2154. if (AutoSize) {
  2155. // Note this is global to this function and used as such within the local functions defined
  2156. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  2157. autosize = GetAutoSize ();
  2158. }
  2159. // Returns the new dimension (width or height) and location (x or y) for the View given
  2160. // the superview's Frame.X or Frame.Y
  2161. // the superview's width or height
  2162. // the current Pos (View.X or View.Y)
  2163. // the current Dim (View.Width or View.Height)
  2164. (int newLocation, int newDimension) GetNewLocationAndDimension (int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
  2165. {
  2166. int newDimension, newLocation;
  2167. switch (pos) {
  2168. case Pos.PosCenter:
  2169. if (dim == null) {
  2170. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  2171. } else {
  2172. newDimension = dim.Anchor (superviewDimension);
  2173. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  2174. }
  2175. newLocation = pos.Anchor (superviewDimension - newDimension);
  2176. break;
  2177. case Pos.PosCombine combine:
  2178. int left, right;
  2179. (left, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.left, dim, autosizeDimension);
  2180. (right, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.right, dim, autosizeDimension);
  2181. if (combine.add) {
  2182. newLocation = left + right;
  2183. } else {
  2184. newLocation = left - right;
  2185. }
  2186. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  2187. break;
  2188. case Pos.PosAbsolute:
  2189. case Pos.PosAnchorEnd:
  2190. case Pos.PosFactor:
  2191. case Pos.PosFunc:
  2192. case Pos.PosView:
  2193. default:
  2194. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  2195. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  2196. break;
  2197. }
  2198. return (newLocation, newDimension);
  2199. }
  2200. // Recursively calculates the new dimension (width or height) of the given Dim given:
  2201. // the current location (x or y)
  2202. // the current dimension (width or height)
  2203. int CalculateNewDimension (Dim d, int location, int dimension, int autosize)
  2204. {
  2205. int newDimension;
  2206. switch (d) {
  2207. case null:
  2208. newDimension = AutoSize ? autosize : dimension;
  2209. break;
  2210. case Dim.DimCombine combine:
  2211. int leftNewDim = CalculateNewDimension (combine.left, location, dimension, autosize);
  2212. int rightNewDim = CalculateNewDimension (combine.right, location, dimension, autosize);
  2213. if (combine.add) {
  2214. newDimension = leftNewDim + rightNewDim;
  2215. } else {
  2216. newDimension = leftNewDim - rightNewDim;
  2217. }
  2218. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2219. break;
  2220. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  2221. newDimension = d.Anchor (dimension);
  2222. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2223. break;
  2224. case Dim.DimFill:
  2225. default:
  2226. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  2227. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2228. break;
  2229. }
  2230. return newDimension;
  2231. }
  2232. // horizontal
  2233. (newX, newW) = GetNewLocationAndDimension (superviewFrame.X, superviewFrame.Width, x, width, autosize.Width);
  2234. // vertical
  2235. (newY, newH) = GetNewLocationAndDimension (superviewFrame.Y, superviewFrame.Height, y, height, autosize.Height);
  2236. var r = new Rect (newX, newY, newW, newH);
  2237. if (Frame != r) {
  2238. Frame = r;
  2239. // BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
  2240. if (!SetMinWidthHeight ()) {
  2241. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2242. }
  2243. }
  2244. }
  2245. /// <summary>
  2246. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2247. /// </summary>
  2248. /// <remarks>
  2249. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2250. /// </remarks>
  2251. public event EventHandler<LayoutEventArgs> LayoutStarted;
  2252. /// <summary>
  2253. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  2254. /// </summary>
  2255. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  2256. {
  2257. LayoutStarted?.Invoke (this, args);
  2258. }
  2259. /// <summary>
  2260. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2261. /// </summary>
  2262. /// <remarks>
  2263. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2264. /// </remarks>
  2265. public event EventHandler<LayoutEventArgs> LayoutComplete;
  2266. /// <summary>
  2267. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  2268. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  2269. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  2270. /// </summary>
  2271. public event EventHandler Initialized;
  2272. /// <summary>
  2273. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  2274. /// </summary>
  2275. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  2276. {
  2277. LayoutComplete?.Invoke (this, args);
  2278. }
  2279. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2280. {
  2281. switch (pos) {
  2282. case Pos.PosView pv:
  2283. // See #2461
  2284. //if (!from.InternalSubviews.Contains (pv.Target)) {
  2285. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  2286. //}
  2287. if (pv.Target != this) {
  2288. nEdges.Add ((pv.Target, from));
  2289. }
  2290. foreach (var v in from.InternalSubviews) {
  2291. CollectAll (v, ref nNodes, ref nEdges);
  2292. }
  2293. return;
  2294. case Pos.PosCombine pc:
  2295. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  2296. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  2297. break;
  2298. }
  2299. }
  2300. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2301. {
  2302. switch (dim) {
  2303. case Dim.DimView dv:
  2304. // See #2461
  2305. //if (!from.InternalSubviews.Contains (dv.Target)) {
  2306. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  2307. //}
  2308. if (dv.Target != this) {
  2309. nEdges.Add ((dv.Target, from));
  2310. }
  2311. foreach (var v in from.InternalSubviews) {
  2312. CollectAll (v, ref nNodes, ref nEdges);
  2313. }
  2314. return;
  2315. case Dim.DimCombine dc:
  2316. CollectDim (dc.left, from, ref nNodes, ref nEdges);
  2317. CollectDim (dc.right, from, ref nNodes, ref nEdges);
  2318. break;
  2319. }
  2320. }
  2321. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2322. {
  2323. foreach (var v in from.InternalSubviews) {
  2324. nNodes.Add (v);
  2325. if (v._layoutStyle != LayoutStyle.Computed) {
  2326. continue;
  2327. }
  2328. CollectPos (v.X, v, ref nNodes, ref nEdges);
  2329. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  2330. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  2331. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  2332. }
  2333. }
  2334. // https://en.wikipedia.org/wiki/Topological_sorting
  2335. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  2336. {
  2337. var result = new List<View> ();
  2338. // Set of all nodes with no incoming edges
  2339. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  2340. while (noEdgeNodes.Any ()) {
  2341. // remove a node n from S
  2342. var n = noEdgeNodes.First ();
  2343. noEdgeNodes.Remove (n);
  2344. // add n to tail of L
  2345. if (n != superView)
  2346. result.Add (n);
  2347. // for each node m with an edge e from n to m do
  2348. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  2349. var m = e.To;
  2350. // remove edge e from the graph
  2351. edges.Remove (e);
  2352. // if m has no other incoming edges then
  2353. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  2354. // insert m into S
  2355. noEdgeNodes.Add (m);
  2356. }
  2357. }
  2358. }
  2359. if (edges.Any ()) {
  2360. foreach ((var from, var to) in edges) {
  2361. if (from == to || from?.SuperView == to?.SuperView) {
  2362. // if not yet added to the result, add it and remove from edge
  2363. if (result.Find (v => v == from) == null) {
  2364. result.Add (from);
  2365. } else if (result.Find (v => v == to) == null) {
  2366. result.Add (to);
  2367. }
  2368. edges.Remove ((from, to));
  2369. } else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to)) {
  2370. if (ReferenceEquals (from.SuperView, to)) {
  2371. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
  2372. } else {
  2373. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
  2374. }
  2375. }
  2376. }
  2377. }
  2378. // return L (a topologically sorted order)
  2379. return result;
  2380. } // TopologicalSort
  2381. /// <summary>
  2382. /// Overriden by <see cref="Frame"/> to do nothing, as the <see cref="Frame"/> does not have frames.
  2383. /// </summary>
  2384. internal virtual void LayoutFrames ()
  2385. {
  2386. if (Margin == null) return; // CreateFrames() has not been called yet
  2387. if (Margin.Frame.Size != Frame.Size) {
  2388. Margin.X = 0;
  2389. Margin.Y = 0;
  2390. Margin.Width = Frame.Size.Width;
  2391. Margin.Height = Frame.Size.Height;
  2392. Margin.SetNeedsLayout ();
  2393. Margin.LayoutSubviews ();
  2394. Margin.SetNeedsDisplay ();
  2395. }
  2396. var border = Margin.Thickness.GetInside (Margin.Frame);
  2397. if (border != BorderFrame.Frame) {
  2398. BorderFrame.X = border.Location.X;
  2399. BorderFrame.Y = border.Location.Y;
  2400. BorderFrame.Width = border.Size.Width;
  2401. BorderFrame.Height = border.Size.Height;
  2402. BorderFrame.SetNeedsLayout ();
  2403. BorderFrame.LayoutSubviews ();
  2404. BorderFrame.SetNeedsDisplay ();
  2405. }
  2406. var padding = BorderFrame.Thickness.GetInside (BorderFrame.Frame);
  2407. if (padding != Padding.Frame) {
  2408. Padding.X = padding.Location.X;
  2409. Padding.Y = padding.Location.Y;
  2410. Padding.Width = padding.Size.Width;
  2411. Padding.Height = padding.Size.Height;
  2412. Padding.SetNeedsLayout ();
  2413. Padding.LayoutSubviews ();
  2414. Padding.SetNeedsDisplay ();
  2415. }
  2416. }
  2417. /// <summary>
  2418. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  2419. /// response to the container view or terminal resizing.
  2420. /// </summary>
  2421. /// <remarks>
  2422. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  2423. /// </remarks>
  2424. public virtual void LayoutSubviews ()
  2425. {
  2426. if (!LayoutNeeded) {
  2427. return;
  2428. }
  2429. LayoutFrames ();
  2430. var oldBounds = Bounds;
  2431. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  2432. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2433. // Sort out the dependencies of the X, Y, Width, Height properties
  2434. var nodes = new HashSet<View> ();
  2435. var edges = new HashSet<(View, View)> ();
  2436. CollectAll (this, ref nodes, ref edges);
  2437. var ordered = View.TopologicalSort (SuperView, nodes, edges);
  2438. foreach (var v in ordered) {
  2439. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  2440. }
  2441. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  2442. // Use LayoutSubview with the Frame of the 'from'
  2443. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded && edges.Count > 0) {
  2444. foreach ((var from, var to) in edges) {
  2445. LayoutSubview (to, from.Frame);
  2446. }
  2447. }
  2448. LayoutNeeded = false;
  2449. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  2450. }
  2451. private void LayoutSubview (View v, Rect contentArea)
  2452. {
  2453. if (v.LayoutStyle == LayoutStyle.Computed) {
  2454. v.SetRelativeLayout (contentArea);
  2455. }
  2456. v.LayoutSubviews ();
  2457. v.LayoutNeeded = false;
  2458. }
  2459. ustring text;
  2460. /// <summary>
  2461. /// The text displayed by the <see cref="View"/>.
  2462. /// </summary>
  2463. /// <remarks>
  2464. /// <para>
  2465. /// If provided, the text will be drawn before any subviews are drawn.
  2466. /// </para>
  2467. /// <para>
  2468. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  2469. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  2470. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  2471. /// is 1, the text will be clipped.
  2472. /// </para>
  2473. /// <para>
  2474. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  2475. /// <c>(Rune)0xffff</c>.
  2476. /// </para>
  2477. /// </remarks>
  2478. public virtual ustring Text {
  2479. get => text;
  2480. set {
  2481. text = value;
  2482. if (IsInitialized) {
  2483. SetHotKey ();
  2484. UpdateTextFormatterText ();
  2485. OnResizeNeeded ();
  2486. }
  2487. // BUGBUG: v2 - This is here as a HACK until we fix the unit tests to not check a view's dims until
  2488. // after it's been initialized. See #2450
  2489. UpdateTextFormatterText ();
  2490. #if DEBUG
  2491. if (text != null && string.IsNullOrEmpty (Id)) {
  2492. Id = text.ToString ();
  2493. }
  2494. #endif
  2495. }
  2496. }
  2497. /// <summary>
  2498. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  2499. /// within <see cref="Bounds"/>
  2500. /// <para>
  2501. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If <see langword="true"/> then
  2502. /// <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can fit;
  2503. /// if <see cref="Text"/> won't fit the view will be resized as needed.
  2504. /// </para>
  2505. /// <para>
  2506. /// In addition, if <see cref="ForceValidatePosDim"/> is <see langword="true"/> the new values of <see cref="Width"/> and
  2507. /// <see cref="Height"/> must be of the same types of the existing one to avoid breaking the <see cref="Dim"/> settings.
  2508. /// </para>
  2509. /// </summary>
  2510. public virtual bool AutoSize {
  2511. get => autoSize;
  2512. set {
  2513. var v = ResizeView (value);
  2514. TextFormatter.AutoSize = v;
  2515. if (autoSize != v) {
  2516. autoSize = v;
  2517. TextFormatter.NeedsFormat = true;
  2518. UpdateTextFormatterText ();
  2519. OnResizeNeeded ();
  2520. }
  2521. }
  2522. }
  2523. /// <summary>
  2524. /// Gets or sets a flag that determines whether <see cref="Terminal.Gui.TextFormatter.Text"/> will have trailing spaces preserved
  2525. /// or not when <see cref="Terminal.Gui.TextFormatter.WordWrap"/> is enabled. If <see langword="true"/>
  2526. /// any trailing spaces will be trimmed when either the <see cref="Text"/> property is changed or
  2527. /// when <see cref="Terminal.Gui.TextFormatter.WordWrap"/> is set to <see langword="true"/>.
  2528. /// The default is <see langword="false"/>.
  2529. /// </summary>
  2530. public virtual bool PreserveTrailingSpaces {
  2531. get => TextFormatter.PreserveTrailingSpaces;
  2532. set {
  2533. if (TextFormatter.PreserveTrailingSpaces != value) {
  2534. TextFormatter.PreserveTrailingSpaces = value;
  2535. TextFormatter.NeedsFormat = true;
  2536. }
  2537. }
  2538. }
  2539. /// <summary>
  2540. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  2541. /// </summary>
  2542. /// <value>The text alignment.</value>
  2543. public virtual TextAlignment TextAlignment {
  2544. get => TextFormatter.Alignment;
  2545. set {
  2546. TextFormatter.Alignment = value;
  2547. UpdateTextFormatterText ();
  2548. OnResizeNeeded ();
  2549. }
  2550. }
  2551. /// <summary>
  2552. /// Gets or sets how the View's <see cref="Text"/> is aligned vertically when drawn. Changing this property will redisplay the <see cref="View"/>.
  2553. /// </summary>
  2554. /// <value>The text alignment.</value>
  2555. public virtual VerticalTextAlignment VerticalTextAlignment {
  2556. get => TextFormatter.VerticalAlignment;
  2557. set {
  2558. TextFormatter.VerticalAlignment = value;
  2559. SetNeedsDisplay ();
  2560. }
  2561. }
  2562. /// <summary>
  2563. /// Gets or sets the direction of the View's <see cref="Text"/>. Changing this property will redisplay the <see cref="View"/>.
  2564. /// </summary>
  2565. /// <value>The text alignment.</value>
  2566. public virtual TextDirection TextDirection {
  2567. get => TextFormatter.Direction;
  2568. set {
  2569. if (!IsInitialized) {
  2570. TextFormatter.Direction = value;
  2571. } else {
  2572. UpdateTextDirection (value);
  2573. }
  2574. }
  2575. }
  2576. private void UpdateTextDirection (TextDirection newDirection)
  2577. {
  2578. var directionChanged = TextFormatter.IsHorizontalDirection (TextFormatter.Direction)
  2579. != TextFormatter.IsHorizontalDirection (newDirection);
  2580. TextFormatter.Direction = newDirection;
  2581. var isValidOldAutoSize = autoSize && IsValidAutoSize (out var _);
  2582. UpdateTextFormatterText ();
  2583. if ((!ForceValidatePosDim && directionChanged && AutoSize)
  2584. || (ForceValidatePosDim && directionChanged && AutoSize && isValidOldAutoSize)) {
  2585. OnResizeNeeded ();
  2586. } else if (directionChanged && IsAdded) {
  2587. SetWidthHeight (Bounds.Size);
  2588. SetMinWidthHeight ();
  2589. } else {
  2590. SetMinWidthHeight ();
  2591. }
  2592. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2593. SetNeedsDisplay ();
  2594. }
  2595. /// <summary>
  2596. /// Get or sets if the <see cref="View"/> has been initialized (via <see cref="ISupportInitialize.BeginInit"/>
  2597. /// and <see cref="ISupportInitialize.EndInit"/>).
  2598. /// </summary>
  2599. /// <para>
  2600. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification.IsInitialized"/>
  2601. /// can be implemented, in which case the <see cref="ISupportInitialize"/>
  2602. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  2603. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  2604. /// to override base class layout code optimally by doing so only on first run,
  2605. /// instead of on every run.
  2606. /// </para>
  2607. public virtual bool IsInitialized { get; set; }
  2608. /// <summary>
  2609. /// Gets information if the view was already added to the <see cref="SuperView"/>.
  2610. /// </summary>
  2611. public bool IsAdded { get; private set; }
  2612. bool oldEnabled;
  2613. /// <inheritdoc/>
  2614. public override bool Enabled {
  2615. get => base.Enabled;
  2616. set {
  2617. if (base.Enabled != value) {
  2618. if (value) {
  2619. if (SuperView == null || SuperView?.Enabled == true) {
  2620. base.Enabled = value;
  2621. }
  2622. } else {
  2623. base.Enabled = value;
  2624. }
  2625. if (!value && HasFocus) {
  2626. SetHasFocus (false, this);
  2627. }
  2628. OnEnabledChanged ();
  2629. SetNeedsDisplay ();
  2630. if (subviews != null) {
  2631. foreach (var view in subviews) {
  2632. if (!value) {
  2633. view.oldEnabled = view.Enabled;
  2634. view.Enabled = false;
  2635. } else {
  2636. view.Enabled = view.oldEnabled;
  2637. view.addingView = false;
  2638. }
  2639. }
  2640. }
  2641. }
  2642. }
  2643. }
  2644. /// <summary>
  2645. /// Gets or sets whether a view is cleared if the <see cref="Visible"/> property is <see langword="false"/>.
  2646. /// </summary>
  2647. public bool ClearOnVisibleFalse { get; set; } = true;
  2648. /// <inheritdoc/>>
  2649. public override bool Visible {
  2650. get => base.Visible;
  2651. set {
  2652. if (base.Visible != value) {
  2653. base.Visible = value;
  2654. if (!value) {
  2655. if (HasFocus) {
  2656. SetHasFocus (false, this);
  2657. }
  2658. if (ClearOnVisibleFalse) {
  2659. Clear ();
  2660. }
  2661. }
  2662. OnVisibleChanged ();
  2663. SetNeedsDisplay ();
  2664. }
  2665. }
  2666. }
  2667. // TODO: v2 Nuke teh Border property (rename BorderFrame to Border)
  2668. Border border;
  2669. /// <inheritdoc/>
  2670. public virtual Border Border {
  2671. get => border;
  2672. set {
  2673. if (border != value) {
  2674. border = value;
  2675. SetNeedsDisplay ();
  2676. if (border != null) {
  2677. Border_BorderChanged (border);
  2678. border.BorderChanged += Border_BorderChanged;
  2679. }
  2680. }
  2681. }
  2682. }
  2683. // TODO: v2 nuke This
  2684. /// <summary>
  2685. /// </summary>
  2686. public virtual bool IgnoreBorderPropertyOnRedraw { get; set; }
  2687. /// <summary>
  2688. /// Pretty prints the View
  2689. /// </summary>
  2690. /// <returns></returns>
  2691. public override string ToString ()
  2692. {
  2693. return $"{GetType ().Name}({Id})({Frame})";
  2694. }
  2695. void SetHotKey ()
  2696. {
  2697. if (TextFormatter == null) {
  2698. return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
  2699. }
  2700. TextFormatter.FindHotKey (text, HotKeySpecifier, true, out _, out var hk);
  2701. if (hotKey != hk) {
  2702. HotKey = hk;
  2703. }
  2704. }
  2705. bool ResizeView (bool autoSize)
  2706. {
  2707. if (!autoSize) {
  2708. return false;
  2709. }
  2710. var aSize = true;
  2711. var nBoundsSize = GetAutoSize ();
  2712. if (nBoundsSize != Bounds.Size) {
  2713. if (ForceValidatePosDim) {
  2714. aSize = SetWidthHeight (nBoundsSize);
  2715. } else {
  2716. Height = nBoundsSize.Height;
  2717. Width = nBoundsSize.Width; // = new Rect (Bounds.X, Bounds.Y, nBoundsSize.Width, nBoundsSize.Height);
  2718. }
  2719. }
  2720. // BUGBUG: This call may be redundant
  2721. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2722. return aSize;
  2723. }
  2724. /// <summary>
  2725. /// Resizes the View to fit the specified <see cref="Bounds"/> size.
  2726. /// </summary>
  2727. /// <param name="nBounds"></param>
  2728. /// <returns></returns>
  2729. bool SetWidthHeight (Size nBounds)
  2730. {
  2731. var aSize = false;
  2732. var canSizeW = TrySetWidth (nBounds.Width - GetHotKeySpecifierLength (), out var rW);
  2733. var canSizeH = TrySetHeight (nBounds.Height - GetHotKeySpecifierLength (false), out var rH);
  2734. if (canSizeW) {
  2735. aSize = true;
  2736. width = rW;
  2737. }
  2738. if (canSizeH) {
  2739. aSize = true;
  2740. height = rH;
  2741. }
  2742. if (aSize) {
  2743. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  2744. }
  2745. return aSize;
  2746. }
  2747. /// <summary>
  2748. /// Gets the dimensions required to fit <see cref="Text"/> using the text <see cref="Direction"/> specified by the
  2749. /// <see cref="TextFormatter"/> property and accounting for any <see cref="HotKeySpecifier"/> characters.
  2750. /// .
  2751. /// </summary>
  2752. /// <returns>The <see cref="Size"/> required to fit the text.</returns>
  2753. public Size GetAutoSize ()
  2754. {
  2755. var rect = TextFormatter.CalcRect (Bounds.X, Bounds.Y, TextFormatter.Text, TextFormatter.Direction);
  2756. return new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2757. rect.Size.Height - GetHotKeySpecifierLength (false));
  2758. }
  2759. bool IsValidAutoSize (out Size autoSize)
  2760. {
  2761. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2762. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2763. rect.Size.Height - GetHotKeySpecifierLength (false));
  2764. return !(ForceValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  2765. || frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  2766. || frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  2767. }
  2768. bool IsValidAutoSizeWidth (Dim width)
  2769. {
  2770. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2771. var dimValue = width.Anchor (0);
  2772. return !(ForceValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
  2773. - GetHotKeySpecifierLength ());
  2774. }
  2775. bool IsValidAutoSizeHeight (Dim height)
  2776. {
  2777. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2778. var dimValue = height.Anchor (0);
  2779. return !(ForceValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
  2780. - GetHotKeySpecifierLength (false));
  2781. }
  2782. /// <summary>
  2783. /// Gets the width or height of the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> characters
  2784. /// in the <see cref="Text"/> property.
  2785. /// </summary>
  2786. /// <remarks>
  2787. /// Only the first hotkey specifier found in <see cref="Text"/> is supported.
  2788. /// </remarks>
  2789. /// <param name="isWidth">If <see langword="true"/> (the default) the width required for the hotkey specifier is returned. Otherwise the height is returned.</param>
  2790. /// <returns>The number of characters required for the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>. If the text direction specified
  2791. /// by <see cref="TextDirection"/> does not match the <paramref name="isWidth"/> parameter, <c>0</c> is returned.</returns>
  2792. public int GetHotKeySpecifierLength (bool isWidth = true)
  2793. {
  2794. if (isWidth) {
  2795. return TextFormatter.IsHorizontalDirection (TextDirection) &&
  2796. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2797. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2798. } else {
  2799. return TextFormatter.IsVerticalDirection (TextDirection) &&
  2800. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2801. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2802. }
  2803. }
  2804. /// <summary>
  2805. /// Gets the dimensions required for <see cref="Text"/> ignoring a <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>.
  2806. /// </summary>
  2807. /// <returns></returns>
  2808. public Size GetSizeNeededForTextWithoutHotKey ()
  2809. {
  2810. return new Size (TextFormatter.Size.Width - GetHotKeySpecifierLength (),
  2811. TextFormatter.Size.Height - GetHotKeySpecifierLength (false));
  2812. }
  2813. /// <summary>
  2814. /// Gets the dimensions required for <see cref="Text"/> accounting for a <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> .
  2815. /// </summary>
  2816. /// <returns></returns>
  2817. public Size GetSizeNeededForTextAndHotKey ()
  2818. {
  2819. if (ustring.IsNullOrEmpty (TextFormatter.Text)) {
  2820. if (!IsInitialized) return Size.Empty;
  2821. return Bounds.Size;
  2822. }
  2823. // BUGBUG: This IGNORES what Text is set to, using on only the current View size. This doesn't seem to make sense.
  2824. // BUGBUG: This uses Frame; in v2 it should be Bounds
  2825. return new Size (frame.Size.Width + GetHotKeySpecifierLength (),
  2826. frame.Size.Height + GetHotKeySpecifierLength (false));
  2827. }
  2828. /// <inheritdoc/>
  2829. public override bool OnMouseEnter (MouseEvent mouseEvent)
  2830. {
  2831. if (!Enabled) {
  2832. return true;
  2833. }
  2834. if (!CanBeVisible (this)) {
  2835. return false;
  2836. }
  2837. var args = new MouseEventEventArgs (mouseEvent);
  2838. MouseEnter?.Invoke (this, args);
  2839. return args.Handled || base.OnMouseEnter (mouseEvent);
  2840. }
  2841. /// <inheritdoc/>
  2842. public override bool OnMouseLeave (MouseEvent mouseEvent)
  2843. {
  2844. if (!Enabled) {
  2845. return true;
  2846. }
  2847. if (!CanBeVisible (this)) {
  2848. return false;
  2849. }
  2850. var args = new MouseEventEventArgs (mouseEvent);
  2851. MouseLeave?.Invoke (this, args);
  2852. return args.Handled || base.OnMouseLeave (mouseEvent);
  2853. }
  2854. /// <summary>
  2855. /// Method invoked when a mouse event is generated
  2856. /// </summary>
  2857. /// <param name="mouseEvent"></param>
  2858. /// <returns><see langword="true"/>, if the event was handled, <see langword="false"/> otherwise.</returns>
  2859. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  2860. {
  2861. if (!Enabled) {
  2862. return true;
  2863. }
  2864. if (!CanBeVisible (this)) {
  2865. return false;
  2866. }
  2867. var args = new MouseEventEventArgs (mouseEvent);
  2868. if (OnMouseClick (args))
  2869. return true;
  2870. if (MouseEvent (mouseEvent))
  2871. return true;
  2872. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  2873. if (CanFocus && !HasFocus && SuperView != null) {
  2874. SuperView.SetFocus (this);
  2875. SetNeedsDisplay ();
  2876. }
  2877. return true;
  2878. }
  2879. return false;
  2880. }
  2881. /// <summary>
  2882. /// Invokes the MouseClick event.
  2883. /// </summary>
  2884. protected bool OnMouseClick (MouseEventEventArgs args)
  2885. {
  2886. if (!Enabled) {
  2887. return true;
  2888. }
  2889. MouseClick?.Invoke (this, args);
  2890. return args.Handled;
  2891. }
  2892. /// <inheritdoc/>
  2893. public override void OnCanFocusChanged () => CanFocusChanged?.Invoke (this, EventArgs.Empty);
  2894. /// <inheritdoc/>
  2895. public override void OnEnabledChanged () => EnabledChanged?.Invoke (this, EventArgs.Empty);
  2896. /// <inheritdoc/>
  2897. public override void OnVisibleChanged () => VisibleChanged?.Invoke (this, EventArgs.Empty);
  2898. /// <inheritdoc/>
  2899. protected override void Dispose (bool disposing)
  2900. {
  2901. Margin?.Dispose ();
  2902. Margin = null;
  2903. BorderFrame?.Dispose ();
  2904. Border = null;
  2905. Padding?.Dispose ();
  2906. Padding = null;
  2907. for (var i = InternalSubviews.Count - 1; i >= 0; i--) {
  2908. var subview = InternalSubviews [i];
  2909. Remove (subview);
  2910. subview.Dispose ();
  2911. }
  2912. base.Dispose (disposing);
  2913. }
  2914. /// <summary>
  2915. /// Signals the View that initialization is starting. See <see cref="ISupportInitialize"/>.
  2916. /// </summary>
  2917. /// <remarks>
  2918. /// <para>
  2919. /// Views can opt-in to more sophisticated initialization
  2920. /// by implementing overrides to <see cref="ISupportInitialize.BeginInit"/> and
  2921. /// <see cref="ISupportInitialize.EndInit"/> which will be called
  2922. /// when the view is added to a <see cref="SuperView"/>.
  2923. /// </para>
  2924. /// <para>
  2925. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification"/>
  2926. /// can be implemented too, in which case the <see cref="ISupportInitialize"/>
  2927. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  2928. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  2929. /// to override base class layout code optimally by doing so only on first run,
  2930. /// instead of on every run.
  2931. /// </para>
  2932. /// </remarks>
  2933. public virtual void BeginInit ()
  2934. {
  2935. if (!IsInitialized) {
  2936. oldCanFocus = CanFocus;
  2937. oldTabIndex = tabIndex;
  2938. UpdateTextDirection (TextDirection);
  2939. UpdateTextFormatterText ();
  2940. SetHotKey ();
  2941. // TODO: Figure out why ScrollView and other tests fail if this call is put here
  2942. // instead of the constructor.
  2943. OnResizeNeeded ();
  2944. //InitializeFrames ();
  2945. } else {
  2946. //throw new InvalidOperationException ("The view is already initialized.");
  2947. }
  2948. if (subviews?.Count > 0) {
  2949. foreach (var view in subviews) {
  2950. if (!view.IsInitialized) {
  2951. view.BeginInit ();
  2952. }
  2953. }
  2954. }
  2955. }
  2956. /// <summary>
  2957. /// Signals the View that initialization is ending. See <see cref="ISupportInitialize"/>.
  2958. /// </summary>
  2959. public void EndInit ()
  2960. {
  2961. IsInitialized = true;
  2962. if (subviews != null) {
  2963. foreach (var view in subviews) {
  2964. if (!view.IsInitialized) {
  2965. view.EndInit ();
  2966. }
  2967. }
  2968. }
  2969. Initialized?.Invoke (this, EventArgs.Empty);
  2970. }
  2971. bool CanBeVisible (View view)
  2972. {
  2973. if (!view.Visible) {
  2974. return false;
  2975. }
  2976. for (var c = view.SuperView; c != null; c = c.SuperView) {
  2977. if (!c.Visible) {
  2978. return false;
  2979. }
  2980. }
  2981. return true;
  2982. }
  2983. /// <summary>
  2984. /// Determines if the View's <see cref="Width"/> can be set to a new value.
  2985. /// </summary>
  2986. /// <param name="desiredWidth"></param>
  2987. /// <param name="resultWidth">Contains the width that would result if <see cref="Width"/> were set to <paramref name="desiredWidth"/>"/> </param>
  2988. /// <returns><see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False otherwise.</returns>
  2989. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  2990. {
  2991. var w = desiredWidth;
  2992. bool canSetWidth;
  2993. switch (Width) {
  2994. case Dim.DimCombine _:
  2995. case Dim.DimView _:
  2996. case Dim.DimFill _:
  2997. // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  2998. w = Width.Anchor (w);
  2999. canSetWidth = !ForceValidatePosDim;
  3000. break;
  3001. case Dim.DimFactor factor:
  3002. // Tries to get the SuperView Width otherwise the view Width.
  3003. var sw = SuperView != null ? SuperView.Frame.Width : w;
  3004. if (factor.IsFromRemaining ()) {
  3005. sw -= Frame.X;
  3006. }
  3007. w = Width.Anchor (sw);
  3008. canSetWidth = !ForceValidatePosDim;
  3009. break;
  3010. default:
  3011. canSetWidth = true;
  3012. break;
  3013. }
  3014. resultWidth = w;
  3015. return canSetWidth;
  3016. }
  3017. /// <summary>
  3018. /// Determines if the View's <see cref="Height"/> can be set to a new value.
  3019. /// </summary>
  3020. /// <param name="desiredHeight"></param>
  3021. /// <param name="resultHeight">Contains the width that would result if <see cref="Height"/> were set to <paramref name="desiredHeight"/>"/> </param>
  3022. /// <returns><see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False otherwise.</returns>
  3023. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  3024. {
  3025. var h = desiredHeight;
  3026. bool canSetHeight;
  3027. switch (Height) {
  3028. case Dim.DimCombine _:
  3029. case Dim.DimView _:
  3030. case Dim.DimFill _:
  3031. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  3032. h = Height.Anchor (h);
  3033. canSetHeight = !ForceValidatePosDim;
  3034. break;
  3035. case Dim.DimFactor factor:
  3036. // Tries to get the SuperView height otherwise the view height.
  3037. var sh = SuperView != null ? SuperView.Frame.Height : h;
  3038. if (factor.IsFromRemaining ()) {
  3039. sh -= Frame.Y;
  3040. }
  3041. h = Height.Anchor (sh);
  3042. canSetHeight = !ForceValidatePosDim;
  3043. break;
  3044. default:
  3045. canSetHeight = true;
  3046. break;
  3047. }
  3048. resultHeight = h;
  3049. return canSetHeight;
  3050. }
  3051. /// <summary>
  3052. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3053. /// </summary>
  3054. /// <returns><see cref="Terminal.Gui.ColorScheme.Normal"/> if <see cref="Enabled"/> is <see langword="true"/>
  3055. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3056. /// If it's overridden can return other values.</returns>
  3057. public virtual Attribute GetNormalColor ()
  3058. {
  3059. return Enabled ? ColorScheme.Normal : ColorScheme.Disabled;
  3060. }
  3061. /// <summary>
  3062. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3063. /// </summary>
  3064. /// <returns><see cref="Terminal.Gui.ColorScheme.Focus"/> if <see cref="Enabled"/> is <see langword="true"/>
  3065. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3066. /// If it's overridden can return other values.</returns>
  3067. public virtual Attribute GetFocusColor ()
  3068. {
  3069. return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  3070. }
  3071. /// <summary>
  3072. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3073. /// </summary>
  3074. /// <returns><see cref="Terminal.Gui.ColorScheme.HotNormal"/> if <see cref="Enabled"/> is <see langword="true"/>
  3075. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3076. /// If it's overridden can return other values.</returns>
  3077. public virtual Attribute GetHotNormalColor ()
  3078. {
  3079. return Enabled ? ColorScheme.HotNormal : ColorScheme.Disabled;
  3080. }
  3081. /// <summary>
  3082. /// Get the top superview of a given <see cref="View"/>.
  3083. /// </summary>
  3084. /// <returns>The superview view.</returns>
  3085. public View GetTopSuperView (View view = null, View superview = null)
  3086. {
  3087. View top = superview ?? Application.Top;
  3088. for (var v = view?.SuperView ?? (this?.SuperView); v != null; v = v.SuperView) {
  3089. top = v;
  3090. if (top == superview) {
  3091. break;
  3092. }
  3093. }
  3094. return top;
  3095. }
  3096. /// <summary>
  3097. /// Finds which view that belong to the <paramref name="start"/> superview at the provided location.
  3098. /// </summary>
  3099. /// <param name="start">The superview where to look for.</param>
  3100. /// <param name="x">The column location in the superview.</param>
  3101. /// <param name="y">The row location in the superview.</param>
  3102. /// <param name="resx">The found view screen relative column location.</param>
  3103. /// <param name="resy">The found view screen relative row location.</param>
  3104. /// <returns>
  3105. /// The view that was found at the <praramref name="x"/> and <praramref name="y"/> coordinates.
  3106. /// <see langword="null"/> if no view was found.
  3107. /// </returns>
  3108. public static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  3109. {
  3110. var startFrame = start.Frame;
  3111. if (!startFrame.Contains (x, y)) {
  3112. resx = 0;
  3113. resy = 0;
  3114. return null;
  3115. }
  3116. if (start.InternalSubviews != null) {
  3117. int count = start.InternalSubviews.Count;
  3118. if (count > 0) {
  3119. var boundsOffset = start.GetBoundsOffset ();
  3120. var rx = x - (startFrame.X + boundsOffset.X);
  3121. var ry = y - (startFrame.Y + boundsOffset.Y);
  3122. for (int i = count - 1; i >= 0; i--) {
  3123. View v = start.InternalSubviews [i];
  3124. if (v.Visible && v.Frame.Contains (rx, ry)) {
  3125. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  3126. if (deep == null)
  3127. return v;
  3128. return deep;
  3129. }
  3130. }
  3131. }
  3132. }
  3133. resx = x - startFrame.X;
  3134. resy = y - startFrame.Y;
  3135. return start;
  3136. }
  3137. }
  3138. }