View.cs 115 KB

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