View.cs 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596
  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. LayoutFrames ();
  431. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  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. /// <summary>
  443. /// Thickness where a visual border (drawn using line-drawing glyphs) and the Title are drawn.
  444. /// The Border expands inward; in other words if `Border.Thickness.Top == 2` the border and
  445. /// title will take up the first row and the second row will be filled with spaces.
  446. /// The Border is not part of the View's content and is not clipped by the View's `ClipArea`.
  447. /// </summary>
  448. /// <remarks>
  449. /// <see cref="BorderStyle"/> provides a simple helper for turning a simple border frame on or off.
  450. /// </remarks>
  451. public Frame Border { get; private set; }
  452. /// <summary>
  453. /// Means the Thickness inside of an element that offsets the `Content` from the Border.
  454. /// 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`.
  455. /// </summary>
  456. /// <remarks>
  457. /// (NOTE: in v1 `Padding` is OUTSIDE of the `Border`).
  458. /// </remarks>
  459. public Frame Padding { get; private set; }
  460. /// <summary>
  461. /// Helper to get the total thickness of the <see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/>.
  462. /// </summary>
  463. /// <returns>A thickness that describes the sum of the Frames' thicknesses.</returns>
  464. public Thickness GetFramesThickness ()
  465. {
  466. var left = Margin.Thickness.Left + Border.Thickness.Left + Padding.Thickness.Left;
  467. var top = Margin.Thickness.Top + Border.Thickness.Top + Padding.Thickness.Top;
  468. var right = Margin.Thickness.Right + Border.Thickness.Right + Padding.Thickness.Right;
  469. var bottom = Margin.Thickness.Bottom + Border.Thickness.Bottom + Padding.Thickness.Bottom;
  470. return new Thickness (left, top, right, bottom);
  471. }
  472. /// <summary>
  473. /// 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
  474. /// <see cref="Margin"/>, <see cref="Border"/> and <see cref="Padding"/>.
  475. /// </summary>
  476. public Point GetBoundsOffset () => new Point (Padding?.Thickness.GetInside (Padding.Frame).X ?? 0, Padding?.Thickness.GetInside (Padding.Frame).Y ?? 0);
  477. /// <summary>
  478. /// Creates the view's <see cref="Frame"/> objects. This internal method is overridden by Frame to do nothing
  479. /// to prevent recursion during View construction.
  480. /// </summary>
  481. internal virtual void CreateFrames ()
  482. {
  483. void ThicknessChangedHandler (object sender, EventArgs e)
  484. {
  485. LayoutFrames ();
  486. SetNeedsLayout ();
  487. SetNeedsDisplay ();
  488. }
  489. if (Margin != null) {
  490. Margin.ThicknessChanged -= ThicknessChangedHandler;
  491. Margin.Dispose ();
  492. }
  493. Margin = new Frame () { Id = "Margin", Thickness = new Thickness (0) };
  494. Margin.ThicknessChanged += ThicknessChangedHandler;
  495. Margin.Parent = this;
  496. if (Border != null) {
  497. Border.ThicknessChanged -= ThicknessChangedHandler;
  498. Border.Dispose ();
  499. }
  500. Border = new Frame () { Id = "Border", Thickness = new Thickness (0) };
  501. Border.ThicknessChanged += ThicknessChangedHandler;
  502. Border.Parent = this;
  503. // TODO: Create View.AddAdornment
  504. if (Padding != null) {
  505. Padding.ThicknessChanged -= ThicknessChangedHandler;
  506. Padding.Dispose ();
  507. }
  508. Padding = new Frame () { Id = "Padding", Thickness = new Thickness (0) };
  509. Padding.ThicknessChanged += ThicknessChangedHandler;
  510. Padding.Parent = this;
  511. }
  512. ustring _title = ustring.Empty;
  513. /// <summary>
  514. /// The title to be displayed for this <see cref="View"/>. The title will be displayed if <see cref="Border"/>.<see cref="Thickness.Top"/>
  515. /// is greater than 0.
  516. /// </summary>
  517. /// <value>The title.</value>
  518. public ustring Title {
  519. get => _title;
  520. set {
  521. if (!OnTitleChanging (_title, value)) {
  522. var old = _title;
  523. _title = value;
  524. SetNeedsDisplay ();
  525. #if DEBUG
  526. if (_title != null && string.IsNullOrEmpty (Id)) {
  527. Id = _title.ToString ();
  528. }
  529. #endif // DEBUG
  530. OnTitleChanged (old, _title);
  531. }
  532. }
  533. }
  534. /// <summary>
  535. /// Called before the <see cref="View.Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can be cancelled.
  536. /// </summary>
  537. /// <param name="oldTitle">The <see cref="View.Title"/> that is/has been replaced.</param>
  538. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  539. /// <returns>`true` if an event handler canceled the Title change.</returns>
  540. public virtual bool OnTitleChanging (ustring oldTitle, ustring newTitle)
  541. {
  542. var args = new TitleEventArgs (oldTitle, newTitle);
  543. TitleChanging?.Invoke (this, args);
  544. return args.Cancel;
  545. }
  546. /// <summary>
  547. /// Event fired when the <see cref="View.Title"/> is changing. Set <see cref="TitleEventArgs.Cancel"/> to
  548. /// `true` to cancel the Title change.
  549. /// </summary>
  550. public event EventHandler<TitleEventArgs> TitleChanging;
  551. /// <summary>
  552. /// Called when the <see cref="View.Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event.
  553. /// </summary>
  554. /// <param name="oldTitle">The <see cref="View.Title"/> that is/has been replaced.</param>
  555. /// <param name="newTitle">The new <see cref="View.Title"/> to be replaced.</param>
  556. public virtual void OnTitleChanged (ustring oldTitle, ustring newTitle)
  557. {
  558. var args = new TitleEventArgs (oldTitle, newTitle);
  559. TitleChanged?.Invoke (this, args);
  560. }
  561. /// <summary>
  562. /// Event fired after the <see cref="View.Title"/> has been changed.
  563. /// </summary>
  564. public event EventHandler<TitleEventArgs> TitleChanged;
  565. LayoutStyle _layoutStyle;
  566. /// <summary>
  567. /// Controls how the View's <see cref="Frame"/> is computed during the LayoutSubviews method, if the style is set to
  568. /// <see cref="Terminal.Gui.LayoutStyle.Absolute"/>,
  569. /// LayoutSubviews does not change the <see cref="Frame"/>. If the style is <see cref="Terminal.Gui.LayoutStyle.Computed"/>
  570. /// the <see cref="Frame"/> is updated using
  571. /// the <see cref="X"/>, <see cref="Y"/>, <see cref="Width"/>, and <see cref="Height"/> properties.
  572. /// </summary>
  573. /// <value>The layout style.</value>
  574. public LayoutStyle LayoutStyle {
  575. get => _layoutStyle;
  576. set {
  577. _layoutStyle = value;
  578. SetNeedsLayout ();
  579. }
  580. }
  581. /// <summary>
  582. /// The View-relative rectangle where View content is displayed. SubViews are positioned relative to
  583. /// Bounds.<see cref="Rect.Location">Location</see> (which is always (0, 0)) and <see cref="Redraw(Rect)"/> clips drawing to
  584. /// Bounds.<see cref="Rect.Size">Size</see>.
  585. /// </summary>
  586. /// <value>The bounds.</value>
  587. /// <remarks>
  588. /// <para>
  589. /// The <see cref="Rect.Location"/> of Bounds is always (0, 0). To obtain the offset of the Bounds from the Frame use
  590. /// <see cref="GetBoundsOffset"/>.
  591. /// </para>
  592. /// </remarks>
  593. public virtual Rect Bounds {
  594. get {
  595. #if DEBUG
  596. if (LayoutStyle == LayoutStyle.Computed && !IsInitialized) {
  597. Debug.WriteLine ($"WARNING: Bounds is being accessed before the View has been initialized. This is likely a bug. View: {this}");
  598. }
  599. #endif // DEBUG
  600. var frameRelativeBounds = Padding?.Thickness.GetInside (Padding.Frame) ?? new Rect (default, Frame.Size);
  601. return new Rect (default, frameRelativeBounds.Size);
  602. }
  603. set {
  604. // BUGBUG: Margin etc.. can be null (if typeof(Frame))
  605. Frame = new Rect (Frame.Location,
  606. new Size (
  607. value.Size.Width + Margin.Thickness.Horizontal + Border.Thickness.Horizontal + Padding.Thickness.Horizontal,
  608. value.Size.Height + Margin.Thickness.Vertical + Border.Thickness.Vertical + Padding.Thickness.Vertical
  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 (GetMinimumBounds (out Size size)) {
  782. _frame = new Rect (_frame.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. Frame = rect.IsEmpty ? TextFormatter.CalcRect (0, 0, text, direction) : rect;
  909. OnResizeNeeded ();
  910. CreateFrames ();
  911. LayoutFrames ();
  912. }
  913. /// <summary>
  914. /// Can be overridden if the <see cref="Terminal.Gui.TextFormatter.Text"/> has
  915. /// different format than the default.
  916. /// </summary>
  917. protected virtual void UpdateTextFormatterText ()
  918. {
  919. if (TextFormatter != null) {
  920. TextFormatter.Text = _text;
  921. }
  922. }
  923. /// <summary>
  924. /// Called whenever the view needs to be resized. Sets <see cref="Frame"/> and
  925. /// triggers a <see cref="LayoutSubviews()"/> call. ///
  926. /// </summary>
  927. /// <remarks>
  928. /// Can be overridden if the view resize behavior is different than the default.
  929. /// </remarks>
  930. protected virtual void OnResizeNeeded ()
  931. {
  932. var actX = _x is Pos.PosAbsolute ? _x.Anchor (0) : _frame.X;
  933. var actY = _y is Pos.PosAbsolute ? _y.Anchor (0) : _frame.Y;
  934. if (AutoSize) {
  935. //if (TextAlignment == TextAlignment.Justified) {
  936. // throw new InvalidOperationException ("TextAlignment.Justified cannot be used with AutoSize");
  937. //}
  938. var s = GetAutoSize ();
  939. var w = _width is Dim.DimAbsolute && _width.Anchor (0) > s.Width ? _width.Anchor (0) : s.Width;
  940. var h = _height is Dim.DimAbsolute && _height.Anchor (0) > s.Height ? _height.Anchor (0) : s.Height;
  941. _frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
  942. } else {
  943. var w = _width is Dim.DimAbsolute ? _width.Anchor (0) : _frame.Width;
  944. var h = _height is Dim.DimAbsolute ? _height.Anchor (0) : _frame.Height;
  945. // BUGBUG: v2 - ? - If layoutstyle is absolute, this overwrites the current frame h/w with 0. Hmmm...
  946. // This is needed for DimAbsolute values by setting the frame before LayoutSubViews.
  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. SetMinWidthHeight ();
  952. LayoutFrames ();
  953. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  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. /// Utility function to draw strings that contain a hotkey.
  1355. /// </summary>
  1356. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  1357. /// <param name="hotColor">Hot color.</param>
  1358. /// <param name="normalColor">Normal color.</param>
  1359. /// <remarks>
  1360. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  1361. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  1362. /// </remarks>
  1363. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  1364. {
  1365. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  1366. Application.Driver.SetAttribute (normalColor);
  1367. foreach (var rune in text) {
  1368. if (rune == hotkeySpec) {
  1369. Application.Driver.SetAttribute (hotColor);
  1370. continue;
  1371. }
  1372. Application.Driver.AddRune (rune);
  1373. Application.Driver.SetAttribute (normalColor);
  1374. }
  1375. }
  1376. /// <summary>
  1377. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  1378. /// </summary>
  1379. /// <param name="text">String to display, the underscore before a letter flags the next letter as the hotkey.</param>
  1380. /// <param name="focused">If set to <see langword="true"/> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  1381. /// <param name="scheme">The color scheme to use.</param>
  1382. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  1383. {
  1384. if (focused)
  1385. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  1386. else
  1387. DrawHotString (text, Enabled ? scheme.HotNormal : scheme.Disabled, Enabled ? scheme.Normal : scheme.Disabled);
  1388. }
  1389. /// <summary>
  1390. /// This moves the cursor to the specified column and row in the view.
  1391. /// </summary>
  1392. /// <returns>The move.</returns>
  1393. /// <param name="col">The column to move to, in view-relative coordinates.</param>
  1394. /// <param name="row">the row to move to, in view-relative coordinates.</param>
  1395. /// <param name="clipped">Whether to clip the result of the ViewToScreen method,
  1396. /// If <see langword="true"/>, the <paramref name="col"/> and <paramref name="row"/> values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).</param>
  1397. public void Move (int col, int row, bool clipped = true)
  1398. {
  1399. if (Driver.Rows == 0) {
  1400. return;
  1401. }
  1402. ViewToScreen (col, row, out var rCol, out var rRow, clipped);
  1403. Driver.Move (rCol, rRow);
  1404. }
  1405. /// <summary>
  1406. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1407. /// </summary>
  1408. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1409. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1410. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1411. /// the last focused view. Views should make sure that they place the cursor
  1412. /// in a visually sensible place.
  1413. public virtual void PositionCursor ()
  1414. {
  1415. if (!CanBeVisible (this) || !Enabled) {
  1416. return;
  1417. }
  1418. // BUGBUG: v2 - This needs to support children of Frames too
  1419. if (_focused == null && SuperView != null) {
  1420. SuperView.EnsureFocus ();
  1421. } else if (_focused?.Visible == true && _focused?.Enabled == true && _focused?.Frame.Width > 0 && _focused.Frame.Height > 0) {
  1422. _focused.PositionCursor ();
  1423. } else if (_focused?.Visible == true && _focused?.Enabled == false) {
  1424. _focused = null;
  1425. } else if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
  1426. Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
  1427. } else {
  1428. Move (_frame.X, _frame.Y);
  1429. }
  1430. }
  1431. // BUGBUG: v2 - Seems weird that this is in View and not Responder.
  1432. bool _hasFocus;
  1433. /// <inheritdoc/>
  1434. public override bool HasFocus => _hasFocus;
  1435. void SetHasFocus (bool value, View view, bool force = false)
  1436. {
  1437. if (_hasFocus != value || force) {
  1438. _hasFocus = value;
  1439. if (value) {
  1440. OnEnter (view);
  1441. } else {
  1442. OnLeave (view);
  1443. }
  1444. SetNeedsDisplay ();
  1445. }
  1446. // Remove focus down the chain of subviews if focus is removed
  1447. if (!value && _focused != null) {
  1448. var f = _focused;
  1449. f.OnLeave (view);
  1450. f.SetHasFocus (false, view);
  1451. _focused = null;
  1452. }
  1453. }
  1454. /// <summary>
  1455. /// Method invoked when a subview is being added to this view.
  1456. /// </summary>
  1457. /// <param name="e">Event where <see cref="ViewEventArgs.View"/> is the subview being added.</param>
  1458. public virtual void OnAdded (SuperViewChangedEventArgs e)
  1459. {
  1460. var view = e.Child;
  1461. view.IsAdded = true;
  1462. view.OnResizeNeeded ();
  1463. view._x ??= view._frame.X;
  1464. view._y ??= view._frame.Y;
  1465. view._width ??= view._frame.Width;
  1466. view._height ??= view._frame.Height;
  1467. view.Added?.Invoke (this, e);
  1468. }
  1469. /// <summary>
  1470. /// Method invoked when a subview is being removed from this view.
  1471. /// </summary>
  1472. /// <param name="e">Event args describing the subview being removed.</param>
  1473. public virtual void OnRemoved (SuperViewChangedEventArgs e)
  1474. {
  1475. var view = e.Child;
  1476. view.IsAdded = false;
  1477. view.Removed?.Invoke (this, e);
  1478. }
  1479. /// <inheritdoc/>
  1480. public override bool OnEnter (View view)
  1481. {
  1482. var args = new FocusEventArgs (view);
  1483. Enter?.Invoke (this, args);
  1484. if (args.Handled)
  1485. return true;
  1486. if (base.OnEnter (view))
  1487. return true;
  1488. return false;
  1489. }
  1490. /// <inheritdoc/>
  1491. public override bool OnLeave (View view)
  1492. {
  1493. var args = new FocusEventArgs (view);
  1494. Leave?.Invoke (this, args);
  1495. if (args.Handled)
  1496. return true;
  1497. if (base.OnLeave (view))
  1498. return true;
  1499. return false;
  1500. }
  1501. /// <summary>
  1502. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1503. /// </summary>
  1504. /// <value>The focused.</value>
  1505. public View Focused => _focused;
  1506. /// <summary>
  1507. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1508. /// </summary>
  1509. /// <value>The most focused View.</value>
  1510. public View MostFocused {
  1511. get {
  1512. if (Focused == null)
  1513. return null;
  1514. var most = Focused.MostFocused;
  1515. if (most != null)
  1516. return most;
  1517. return Focused;
  1518. }
  1519. }
  1520. ColorScheme _colorScheme;
  1521. /// <summary>
  1522. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1523. /// color scheme.
  1524. /// </summary>
  1525. public virtual ColorScheme ColorScheme {
  1526. get {
  1527. if (_colorScheme == null) {
  1528. return SuperView?.ColorScheme;
  1529. }
  1530. return _colorScheme;
  1531. }
  1532. set {
  1533. if (_colorScheme != value) {
  1534. _colorScheme = value;
  1535. SetNeedsDisplay ();
  1536. }
  1537. }
  1538. }
  1539. /// <summary>
  1540. /// Displays the specified character in the specified column and row of the View.
  1541. /// </summary>
  1542. /// <param name="col">Column (view-relative).</param>
  1543. /// <param name="row">Row (view-relative).</param>
  1544. /// <param name="ch">Ch.</param>
  1545. public void AddRune (int col, int row, Rune ch)
  1546. {
  1547. if (row < 0 || col < 0)
  1548. return;
  1549. if (row > _frame.Height - 1 || col > _frame.Width - 1)
  1550. return;
  1551. Move (col, row);
  1552. Driver.AddRune (ch);
  1553. }
  1554. /// <summary>
  1555. /// Removes the <see cref="_needsDisplay"/> and the <see cref="_childNeedsDisplay"/> setting on this view.
  1556. /// </summary>
  1557. protected void ClearNeedsDisplay ()
  1558. {
  1559. _needsDisplay = Rect.Empty;
  1560. _childNeedsDisplay = false;
  1561. }
  1562. /// <summary>
  1563. /// The canvas that any line drawing that is to be shared by subviews of this view should add lines to.
  1564. /// </summary>
  1565. /// <remarks><see cref="Border"/> adds border lines to this LineCanvas.</remarks>
  1566. public virtual LineCanvas LineCanvas { get; set; } = new LineCanvas ();
  1567. /// <summary>
  1568. /// Gets or sets whether this View will use it's SuperView's <see cref="LineCanvas"/> for
  1569. /// rendering any border lines. If <see langword="true"/> the rendering of any borders drawn
  1570. /// by this Frame will be done by it's parent's SuperView. If <see langword="false"/> (the default)
  1571. /// this View's <see cref="OnDrawFrames()"/> method will be called to render the borders.
  1572. /// </summary>
  1573. public virtual bool SuperViewRendersLineCanvas { get; set; } = false;
  1574. // TODO: Make this cancelable
  1575. /// <summary>
  1576. ///
  1577. /// </summary>
  1578. /// <returns></returns>
  1579. public virtual bool OnDrawFrames ()
  1580. {
  1581. if (!IsInitialized) {
  1582. return false;
  1583. }
  1584. var prevClip = Driver.Clip;
  1585. Driver.Clip = ViewToScreen (Frame);
  1586. // TODO: Figure out what we should do if we have no superview
  1587. //if (SuperView != null) {
  1588. // TODO: Clipping is disabled for now to ensure we see errors
  1589. Driver.Clip = new Rect (0, 0, Driver.Cols, Driver.Rows);// screenBounds;// SuperView.ClipToBounds ();
  1590. //}
  1591. // Each of these renders lines to either this View's LineCanvas
  1592. // Those lines will be finally rendered in OnRenderLineCanvas
  1593. Margin?.Redraw (Margin.Frame);
  1594. Border?.Redraw (Border.Frame);
  1595. Padding?.Redraw (Padding.Frame);
  1596. Driver.Clip = prevClip;
  1597. return true;
  1598. }
  1599. /// <summary>
  1600. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1601. /// </summary>
  1602. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1603. /// <remarks>
  1604. /// <para>
  1605. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1606. /// </para>
  1607. /// <para>
  1608. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1609. /// the last color that was set globally on the driver.
  1610. /// </para>
  1611. /// <para>
  1612. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1613. /// larger than the <ref name="bounds"/> parameter, as this will cause the driver to clip the entire region.
  1614. /// </para>
  1615. /// </remarks>
  1616. public virtual void Redraw (Rect bounds)
  1617. {
  1618. if (!CanBeVisible (this)) {
  1619. return;
  1620. }
  1621. OnDrawFrames ();
  1622. var prevClip = ClipToBounds ();
  1623. if (ColorScheme != null) {
  1624. //Driver.SetAttribute (HasFocus ? GetFocusColor () : GetNormalColor ());
  1625. Driver.SetAttribute (GetNormalColor ());
  1626. }
  1627. if (SuperView != null) {
  1628. Clear (ViewToScreen (bounds));
  1629. }
  1630. // Invoke DrawContentEvent
  1631. OnDrawContent (bounds);
  1632. // Draw subviews
  1633. // TODO: Implement OnDrawSubviews (cancelable);
  1634. if (_subviews != null) {
  1635. foreach (var view in _subviews) {
  1636. if (view.Visible) { //!view._needsDisplay.IsEmpty || view._childNeedsDisplay || view.LayoutNeeded) {
  1637. if (true) { //view.Frame.IntersectsWith (bounds)) { // && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1638. if (view.LayoutNeeded) {
  1639. view.LayoutSubviews ();
  1640. }
  1641. // Draw the subview
  1642. // Use the view's bounds (view-relative; Location will always be (0,0)
  1643. //if (view.Visible && view.Frame.Width > 0 && view.Frame.Height > 0) {
  1644. view.Redraw (view.Bounds);
  1645. //}
  1646. }
  1647. view.ClearNeedsDisplay ();
  1648. }
  1649. }
  1650. }
  1651. // Invoke DrawContentCompleteEvent
  1652. OnDrawContentComplete (bounds);
  1653. Driver.Clip = prevClip;
  1654. OnRenderLineCanvas ();
  1655. // BUGBUG: v2 - We should be able to use View.SetClip here and not have to resort to knowing Driver details.
  1656. ClearLayoutNeeded ();
  1657. ClearNeedsDisplay ();
  1658. }
  1659. internal void OnRenderLineCanvas ()
  1660. {
  1661. //Driver.SetAttribute (new Attribute(Color.White, Color.Black));
  1662. // If we have a SuperView, it'll render our frames.
  1663. if (!SuperViewRendersLineCanvas && LineCanvas.Bounds != Rect.Empty) {
  1664. foreach (var p in LineCanvas.GetCellMap ()) { // Get the entire map
  1665. Driver.SetAttribute (p.Value.Attribute?.Value ?? ColorScheme.Normal);
  1666. Driver.Move (p.Key.X, p.Key.Y);
  1667. Driver.AddRune (p.Value.Rune.Value);
  1668. }
  1669. LineCanvas.Clear ();
  1670. }
  1671. if (Subviews.Select (s => s.SuperViewRendersLineCanvas).Count () > 0) {
  1672. foreach (var subview in Subviews.Where (s => s.SuperViewRendersLineCanvas)) {
  1673. // Combine the LineCavas'
  1674. LineCanvas.Merge (subview.LineCanvas);
  1675. subview.LineCanvas.Clear ();
  1676. }
  1677. foreach (var p in LineCanvas.GetCellMap ()) { // Get the entire map
  1678. Driver.SetAttribute (p.Value.Attribute?.Value ?? ColorScheme.Normal);
  1679. Driver.Move (p.Key.X, p.Key.Y);
  1680. Driver.AddRune (p.Value.Rune.Value);
  1681. }
  1682. LineCanvas.Clear ();
  1683. }
  1684. }
  1685. /// <summary>
  1686. /// Event invoked when the content area of the View is to be drawn.
  1687. /// </summary>
  1688. /// <remarks>
  1689. /// <para>
  1690. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1691. /// </para>
  1692. /// <para>
  1693. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1694. /// </para>
  1695. /// </remarks>
  1696. public event EventHandler<DrawEventArgs> DrawContent;
  1697. /// <summary>
  1698. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1699. /// </summary>
  1700. /// <param name="contentArea">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1701. /// <remarks>
  1702. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1703. /// </remarks>
  1704. public virtual void OnDrawContent (Rect contentArea)
  1705. {
  1706. // TODO: Make DrawContent a cancelable event
  1707. // if (!DrawContent?.Invoke(this, new DrawEventArgs (viewport)) {
  1708. DrawContent?.Invoke (this, new DrawEventArgs (contentArea));
  1709. if (!ustring.IsNullOrEmpty (TextFormatter.Text)) {
  1710. if (TextFormatter != null) {
  1711. TextFormatter.NeedsFormat = true;
  1712. }
  1713. // This should NOT clear
  1714. TextFormatter?.Draw (ViewToScreen (contentArea), HasFocus ? GetFocusColor () : GetNormalColor (),
  1715. HasFocus ? ColorScheme.HotFocus : GetHotNormalColor (),
  1716. Rect.Empty, false);
  1717. SetSubViewNeedsDisplay ();
  1718. }
  1719. }
  1720. /// <summary>
  1721. /// Event invoked when the content area of the View is completed drawing.
  1722. /// </summary>
  1723. /// <remarks>
  1724. /// <para>
  1725. /// Will be invoked after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1726. /// </para>
  1727. /// <para>
  1728. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1729. /// </para>
  1730. /// </remarks>
  1731. public event EventHandler<DrawEventArgs> DrawContentComplete;
  1732. /// <summary>
  1733. /// Enables overrides after completed drawing infinitely scrolled content and/or a background behind removed controls.
  1734. /// </summary>
  1735. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1736. /// <remarks>
  1737. /// This method will be called after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1738. /// </remarks>
  1739. public virtual void OnDrawContentComplete (Rect viewport)
  1740. {
  1741. DrawContentComplete?.Invoke (this, new DrawEventArgs (viewport));
  1742. }
  1743. /// <summary>
  1744. /// Causes the specified subview to have focus.
  1745. /// </summary>
  1746. /// <param name="view">View.</param>
  1747. void SetFocus (View view)
  1748. {
  1749. if (view == null) {
  1750. return;
  1751. }
  1752. //Console.WriteLine ($"Request to focus {view}");
  1753. if (!view.CanFocus || !view.Visible || !view.Enabled) {
  1754. return;
  1755. }
  1756. if (_focused?._hasFocus == true && _focused == view) {
  1757. return;
  1758. }
  1759. if ((_focused?._hasFocus == true && _focused?.SuperView == view) || view == this) {
  1760. if (!view._hasFocus) {
  1761. view._hasFocus = true;
  1762. }
  1763. return;
  1764. }
  1765. // Make sure that this view is a subview
  1766. View c;
  1767. for (c = view._superView; c != null; c = c._superView)
  1768. if (c == this)
  1769. break;
  1770. if (c == null)
  1771. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1772. if (_focused != null)
  1773. _focused.SetHasFocus (false, view);
  1774. var f = _focused;
  1775. _focused = view;
  1776. _focused.SetHasFocus (true, f);
  1777. _focused.EnsureFocus ();
  1778. // Send focus upwards
  1779. if (SuperView != null) {
  1780. SuperView.SetFocus (this);
  1781. } else {
  1782. SetFocus (this);
  1783. }
  1784. }
  1785. /// <summary>
  1786. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  1787. /// </summary>
  1788. public void SetFocus ()
  1789. {
  1790. if (!CanBeVisible (this) || !Enabled) {
  1791. if (HasFocus) {
  1792. SetHasFocus (false, this);
  1793. }
  1794. return;
  1795. }
  1796. if (SuperView != null) {
  1797. SuperView.SetFocus (this);
  1798. } else {
  1799. SetFocus (this);
  1800. }
  1801. }
  1802. /// <summary>
  1803. /// Invoked when a character key is pressed and occurs after the key up event.
  1804. /// </summary>
  1805. public event EventHandler<KeyEventEventArgs> KeyPress;
  1806. /// <inheritdoc/>
  1807. public override bool ProcessKey (KeyEvent keyEvent)
  1808. {
  1809. if (!Enabled) {
  1810. return false;
  1811. }
  1812. var args = new KeyEventEventArgs (keyEvent);
  1813. KeyPress?.Invoke (this, args);
  1814. if (args.Handled)
  1815. return true;
  1816. if (Focused?.Enabled == true) {
  1817. Focused?.KeyPress?.Invoke (this, args);
  1818. if (args.Handled)
  1819. return true;
  1820. }
  1821. return Focused?.Enabled == true && Focused?.ProcessKey (keyEvent) == true;
  1822. }
  1823. /// <summary>
  1824. /// Invokes any binding that is registered on this <see cref="View"/>
  1825. /// and matches the <paramref name="keyEvent"/>
  1826. /// </summary>
  1827. /// <param name="keyEvent">The key event passed.</param>
  1828. protected bool? InvokeKeybindings (KeyEvent keyEvent)
  1829. {
  1830. bool? toReturn = null;
  1831. if (KeyBindings.ContainsKey (keyEvent.Key)) {
  1832. foreach (var command in KeyBindings [keyEvent.Key]) {
  1833. if (!CommandImplementations.ContainsKey (command)) {
  1834. 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})");
  1835. }
  1836. // each command has its own return value
  1837. var thisReturn = CommandImplementations [command] ();
  1838. // if we haven't got anything yet, the current command result should be used
  1839. if (toReturn == null) {
  1840. toReturn = thisReturn;
  1841. }
  1842. // if ever see a true then that's what we will return
  1843. if (thisReturn ?? false) {
  1844. toReturn = true;
  1845. }
  1846. }
  1847. }
  1848. return toReturn;
  1849. }
  1850. /// <summary>
  1851. /// <para>Adds a new key combination that will trigger the given <paramref name="command"/>
  1852. /// (if supported by the View - see <see cref="GetSupportedCommands"/>)
  1853. /// </para>
  1854. /// <para>If the key is already bound to a different <see cref="Command"/> it will be
  1855. /// rebound to this one</para>
  1856. /// <remarks>Commands are only ever applied to the current <see cref="View"/>(i.e. this feature
  1857. /// cannot be used to switch focus to another view and perform multiple commands there) </remarks>
  1858. /// </summary>
  1859. /// <param name="key"></param>
  1860. /// <param name="command">The command(s) to run on the <see cref="View"/> when <paramref name="key"/> is pressed.
  1861. /// When specifying multiple commands, all commands will be applied in sequence. The bound <paramref name="key"/> strike
  1862. /// will be consumed if any took effect.</param>
  1863. public void AddKeyBinding (Key key, params Command [] command)
  1864. {
  1865. if (command.Length == 0) {
  1866. throw new ArgumentException ("At least one command must be specified", nameof (command));
  1867. }
  1868. if (KeyBindings.ContainsKey (key)) {
  1869. KeyBindings [key] = command;
  1870. } else {
  1871. KeyBindings.Add (key, command);
  1872. }
  1873. }
  1874. /// <summary>
  1875. /// Replaces a key combination already bound to <see cref="Command"/>.
  1876. /// </summary>
  1877. /// <param name="fromKey">The key to be replaced.</param>
  1878. /// <param name="toKey">The new key to be used.</param>
  1879. protected void ReplaceKeyBinding (Key fromKey, Key toKey)
  1880. {
  1881. if (KeyBindings.ContainsKey (fromKey)) {
  1882. var value = KeyBindings [fromKey];
  1883. KeyBindings.Remove (fromKey);
  1884. KeyBindings [toKey] = value;
  1885. }
  1886. }
  1887. /// <summary>
  1888. /// Checks if the key binding already exists.
  1889. /// </summary>
  1890. /// <param name="key">The key to check.</param>
  1891. /// <returns><see langword="true"/> If the key already exist, <see langword="false"/> otherwise.</returns>
  1892. public bool ContainsKeyBinding (Key key)
  1893. {
  1894. return KeyBindings.ContainsKey (key);
  1895. }
  1896. /// <summary>
  1897. /// Removes all bound keys from the View and resets the default bindings.
  1898. /// </summary>
  1899. public void ClearKeybindings ()
  1900. {
  1901. KeyBindings.Clear ();
  1902. }
  1903. /// <summary>
  1904. /// Clears the existing keybinding (if any) for the given <paramref name="key"/>.
  1905. /// </summary>
  1906. /// <param name="key"></param>
  1907. public void ClearKeybinding (Key key)
  1908. {
  1909. KeyBindings.Remove (key);
  1910. }
  1911. /// <summary>
  1912. /// Removes all key bindings that trigger the given command. Views can have multiple different
  1913. /// keys bound to the same command and this method will clear all of them.
  1914. /// </summary>
  1915. /// <param name="command"></param>
  1916. public void ClearKeybinding (params Command [] command)
  1917. {
  1918. foreach (var kvp in KeyBindings.Where (kvp => kvp.Value.SequenceEqual (command)).ToArray ()) {
  1919. KeyBindings.Remove (kvp.Key);
  1920. }
  1921. }
  1922. /// <summary>
  1923. /// <para>States that the given <see cref="View"/> supports a given <paramref name="command"/>
  1924. /// and what <paramref name="f"/> to perform to make that command happen
  1925. /// </para>
  1926. /// <para>If the <paramref name="command"/> already has an implementation the <paramref name="f"/>
  1927. /// will replace the old one</para>
  1928. /// </summary>
  1929. /// <param name="command">The command.</param>
  1930. /// <param name="f">The function.</param>
  1931. protected void AddCommand (Command command, Func<bool?> f)
  1932. {
  1933. // if there is already an implementation of this command
  1934. if (CommandImplementations.ContainsKey (command)) {
  1935. // replace that implementation
  1936. CommandImplementations [command] = f;
  1937. } else {
  1938. // else record how to perform the action (this should be the normal case)
  1939. CommandImplementations.Add (command, f);
  1940. }
  1941. }
  1942. /// <summary>
  1943. /// Returns all commands that are supported by this <see cref="View"/>.
  1944. /// </summary>
  1945. /// <returns></returns>
  1946. public IEnumerable<Command> GetSupportedCommands ()
  1947. {
  1948. return CommandImplementations.Keys;
  1949. }
  1950. /// <summary>
  1951. /// Gets the key used by a command.
  1952. /// </summary>
  1953. /// <param name="command">The command to search.</param>
  1954. /// <returns>The <see cref="Key"/> used by a <see cref="Command"/></returns>
  1955. public Key GetKeyFromCommand (params Command [] command)
  1956. {
  1957. return KeyBindings.First (kb => kb.Value.SequenceEqual (command)).Key;
  1958. }
  1959. /// <inheritdoc/>
  1960. public override bool ProcessHotKey (KeyEvent keyEvent)
  1961. {
  1962. if (!Enabled) {
  1963. return false;
  1964. }
  1965. var args = new KeyEventEventArgs (keyEvent);
  1966. if (MostFocused?.Enabled == true) {
  1967. MostFocused?.KeyPress?.Invoke (this, args);
  1968. if (args.Handled)
  1969. return true;
  1970. }
  1971. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1972. return true;
  1973. if (_subviews == null || _subviews.Count == 0)
  1974. return false;
  1975. foreach (var view in _subviews)
  1976. if (view.Enabled && view.ProcessHotKey (keyEvent))
  1977. return true;
  1978. return false;
  1979. }
  1980. /// <inheritdoc/>
  1981. public override bool ProcessColdKey (KeyEvent keyEvent)
  1982. {
  1983. if (!Enabled) {
  1984. return false;
  1985. }
  1986. var args = new KeyEventEventArgs (keyEvent);
  1987. KeyPress?.Invoke (this, args);
  1988. if (args.Handled)
  1989. return true;
  1990. if (MostFocused?.Enabled == true) {
  1991. MostFocused?.KeyPress?.Invoke (this, args);
  1992. if (args.Handled)
  1993. return true;
  1994. }
  1995. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1996. return true;
  1997. if (_subviews == null || _subviews.Count == 0)
  1998. return false;
  1999. foreach (var view in _subviews)
  2000. if (view.Enabled && view.ProcessColdKey (keyEvent))
  2001. return true;
  2002. return false;
  2003. }
  2004. /// <summary>
  2005. /// Invoked when a key is pressed.
  2006. /// </summary>
  2007. public event EventHandler<KeyEventEventArgs> KeyDown;
  2008. /// <inheritdoc/>
  2009. public override bool OnKeyDown (KeyEvent keyEvent)
  2010. {
  2011. if (!Enabled) {
  2012. return false;
  2013. }
  2014. var args = new KeyEventEventArgs (keyEvent);
  2015. KeyDown?.Invoke (this, args);
  2016. if (args.Handled) {
  2017. return true;
  2018. }
  2019. if (Focused?.Enabled == true) {
  2020. Focused.KeyDown?.Invoke (this, args);
  2021. if (args.Handled) {
  2022. return true;
  2023. }
  2024. if (Focused?.OnKeyDown (keyEvent) == true) {
  2025. return true;
  2026. }
  2027. }
  2028. return false;
  2029. }
  2030. /// <summary>
  2031. /// Invoked when a key is released.
  2032. /// </summary>
  2033. public event EventHandler<KeyEventEventArgs> KeyUp;
  2034. /// <inheritdoc/>
  2035. public override bool OnKeyUp (KeyEvent keyEvent)
  2036. {
  2037. if (!Enabled) {
  2038. return false;
  2039. }
  2040. var args = new KeyEventEventArgs (keyEvent);
  2041. KeyUp?.Invoke (this, args);
  2042. if (args.Handled) {
  2043. return true;
  2044. }
  2045. if (Focused?.Enabled == true) {
  2046. Focused.KeyUp?.Invoke (this, args);
  2047. if (args.Handled) {
  2048. return true;
  2049. }
  2050. if (Focused?.OnKeyUp (keyEvent) == true) {
  2051. return true;
  2052. }
  2053. }
  2054. return false;
  2055. }
  2056. /// <summary>
  2057. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, does nothing.
  2058. /// </summary>
  2059. public void EnsureFocus ()
  2060. {
  2061. if (_focused == null && _subviews?.Count > 0) {
  2062. if (FocusDirection == Direction.Forward) {
  2063. FocusFirst ();
  2064. } else {
  2065. FocusLast ();
  2066. }
  2067. }
  2068. }
  2069. /// <summary>
  2070. /// Focuses the first focusable subview if one exists.
  2071. /// </summary>
  2072. public void FocusFirst ()
  2073. {
  2074. if (!CanBeVisible (this)) {
  2075. return;
  2076. }
  2077. if (_tabIndexes == null) {
  2078. SuperView?.SetFocus (this);
  2079. return;
  2080. }
  2081. foreach (var view in _tabIndexes) {
  2082. if (view.CanFocus && view._tabStop && view.Visible && view.Enabled) {
  2083. SetFocus (view);
  2084. return;
  2085. }
  2086. }
  2087. }
  2088. /// <summary>
  2089. /// Focuses the last focusable subview if one exists.
  2090. /// </summary>
  2091. public void FocusLast ()
  2092. {
  2093. if (!CanBeVisible (this)) {
  2094. return;
  2095. }
  2096. if (_tabIndexes == null) {
  2097. SuperView?.SetFocus (this);
  2098. return;
  2099. }
  2100. for (var i = _tabIndexes.Count; i > 0;) {
  2101. i--;
  2102. var v = _tabIndexes [i];
  2103. if (v.CanFocus && v._tabStop && v.Visible && v.Enabled) {
  2104. SetFocus (v);
  2105. return;
  2106. }
  2107. }
  2108. }
  2109. /// <summary>
  2110. /// Focuses the previous view.
  2111. /// </summary>
  2112. /// <returns><see langword="true"/> if previous was focused, <see langword="false"/> otherwise.</returns>
  2113. public bool FocusPrev ()
  2114. {
  2115. if (!CanBeVisible (this)) {
  2116. return false;
  2117. }
  2118. FocusDirection = Direction.Backward;
  2119. if (_tabIndexes == null || _tabIndexes.Count == 0)
  2120. return false;
  2121. if (_focused == null) {
  2122. FocusLast ();
  2123. return _focused != null;
  2124. }
  2125. var focusedIdx = -1;
  2126. for (var i = _tabIndexes.Count; i > 0;) {
  2127. i--;
  2128. var w = _tabIndexes [i];
  2129. if (w.HasFocus) {
  2130. if (w.FocusPrev ())
  2131. return true;
  2132. focusedIdx = i;
  2133. continue;
  2134. }
  2135. if (w.CanFocus && focusedIdx != -1 && w._tabStop && w.Visible && w.Enabled) {
  2136. _focused.SetHasFocus (false, w);
  2137. if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
  2138. w.FocusLast ();
  2139. SetFocus (w);
  2140. return true;
  2141. }
  2142. }
  2143. if (_focused != null) {
  2144. _focused.SetHasFocus (false, this);
  2145. _focused = null;
  2146. }
  2147. return false;
  2148. }
  2149. /// <summary>
  2150. /// Focuses the next view.
  2151. /// </summary>
  2152. /// <returns><see langword="true"/> if next was focused, <see langword="false"/> otherwise.</returns>
  2153. public bool FocusNext ()
  2154. {
  2155. if (!CanBeVisible (this)) {
  2156. return false;
  2157. }
  2158. FocusDirection = Direction.Forward;
  2159. if (_tabIndexes == null || _tabIndexes.Count == 0)
  2160. return false;
  2161. if (_focused == null) {
  2162. FocusFirst ();
  2163. return _focused != null;
  2164. }
  2165. var focusedIdx = -1;
  2166. for (var i = 0; i < _tabIndexes.Count; i++) {
  2167. var w = _tabIndexes [i];
  2168. if (w.HasFocus) {
  2169. if (w.FocusNext ())
  2170. return true;
  2171. focusedIdx = i;
  2172. continue;
  2173. }
  2174. if (w.CanFocus && focusedIdx != -1 && w._tabStop && w.Visible && w.Enabled) {
  2175. _focused.SetHasFocus (false, w);
  2176. if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
  2177. w.FocusFirst ();
  2178. SetFocus (w);
  2179. return true;
  2180. }
  2181. }
  2182. if (_focused != null) {
  2183. _focused.SetHasFocus (false, this);
  2184. _focused = null;
  2185. }
  2186. return false;
  2187. }
  2188. View GetMostFocused (View view)
  2189. {
  2190. if (view == null) {
  2191. return null;
  2192. }
  2193. return view._focused != null ? GetMostFocused (view._focused) : view;
  2194. }
  2195. /// <summary>
  2196. /// Sets the View's <see cref="Frame"/> to the frame-relative coordinates if its container. The
  2197. /// container size and location are specified by <paramref name="superviewFrame"/> and are relative to the
  2198. /// View's superview.
  2199. /// </summary>
  2200. /// <param name="superviewFrame">The supserview-relative rectangle describing View's container (nominally the
  2201. /// same as <c>this.SuperView.Frame</c>).</param>
  2202. internal void SetRelativeLayout (Rect superviewFrame)
  2203. {
  2204. int newX, newW, newY, newH;
  2205. var autosize = Size.Empty;
  2206. if (AutoSize) {
  2207. // Note this is global to this function and used as such within the local functions defined
  2208. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  2209. autosize = GetAutoSize ();
  2210. }
  2211. // Returns the new dimension (width or height) and location (x or y) for the View given
  2212. // the superview's Frame.X or Frame.Y
  2213. // the superview's width or height
  2214. // the current Pos (View.X or View.Y)
  2215. // the current Dim (View.Width or View.Height)
  2216. (int newLocation, int newDimension) GetNewLocationAndDimension (int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
  2217. {
  2218. int newDimension, newLocation;
  2219. switch (pos) {
  2220. case Pos.PosCenter:
  2221. if (dim == null) {
  2222. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  2223. } else {
  2224. newDimension = dim.Anchor (superviewDimension);
  2225. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  2226. }
  2227. newLocation = pos.Anchor (superviewDimension - newDimension);
  2228. break;
  2229. case Pos.PosCombine combine:
  2230. int left, right;
  2231. (left, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.left, dim, autosizeDimension);
  2232. (right, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.right, dim, autosizeDimension);
  2233. if (combine.add) {
  2234. newLocation = left + right;
  2235. } else {
  2236. newLocation = left - right;
  2237. }
  2238. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  2239. break;
  2240. case Pos.PosAbsolute:
  2241. case Pos.PosAnchorEnd:
  2242. case Pos.PosFactor:
  2243. case Pos.PosFunc:
  2244. case Pos.PosView:
  2245. default:
  2246. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  2247. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  2248. break;
  2249. }
  2250. return (newLocation, newDimension);
  2251. }
  2252. // Recursively calculates the new dimension (width or height) of the given Dim given:
  2253. // the current location (x or y)
  2254. // the current dimension (width or height)
  2255. int CalculateNewDimension (Dim d, int location, int dimension, int autosize)
  2256. {
  2257. int newDimension;
  2258. switch (d) {
  2259. case null:
  2260. newDimension = AutoSize ? autosize : dimension;
  2261. break;
  2262. case Dim.DimCombine combine:
  2263. int leftNewDim = CalculateNewDimension (combine.left, location, dimension, autosize);
  2264. int rightNewDim = CalculateNewDimension (combine.right, location, dimension, autosize);
  2265. if (combine.add) {
  2266. newDimension = leftNewDim + rightNewDim;
  2267. } else {
  2268. newDimension = leftNewDim - rightNewDim;
  2269. }
  2270. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2271. break;
  2272. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  2273. newDimension = d.Anchor (dimension);
  2274. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2275. break;
  2276. case Dim.DimFill:
  2277. default:
  2278. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  2279. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2280. break;
  2281. }
  2282. return newDimension;
  2283. }
  2284. // horizontal
  2285. (newX, newW) = GetNewLocationAndDimension (superviewFrame.X, superviewFrame.Width, _x, _width, autosize.Width);
  2286. // vertical
  2287. (newY, newH) = GetNewLocationAndDimension (superviewFrame.Y, superviewFrame.Height, _y, _height, autosize.Height);
  2288. var r = new Rect (newX, newY, newW, newH);
  2289. if (Frame != r) {
  2290. Frame = r;
  2291. // BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
  2292. if (!SetMinWidthHeight ()) {
  2293. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2294. }
  2295. }
  2296. }
  2297. /// <summary>
  2298. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2299. /// </summary>
  2300. /// <remarks>
  2301. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2302. /// </remarks>
  2303. public event EventHandler<LayoutEventArgs> LayoutStarted;
  2304. /// <summary>
  2305. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  2306. /// </summary>
  2307. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  2308. {
  2309. LayoutStarted?.Invoke (this, args);
  2310. }
  2311. /// <summary>
  2312. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2313. /// </summary>
  2314. /// <remarks>
  2315. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2316. /// </remarks>
  2317. public event EventHandler<LayoutEventArgs> LayoutComplete;
  2318. /// <summary>
  2319. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  2320. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  2321. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  2322. /// </summary>
  2323. public event EventHandler Initialized;
  2324. /// <summary>
  2325. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  2326. /// </summary>
  2327. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  2328. {
  2329. LayoutComplete?.Invoke (this, args);
  2330. }
  2331. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2332. {
  2333. switch (pos) {
  2334. case Pos.PosView pv:
  2335. // See #2461
  2336. //if (!from.InternalSubviews.Contains (pv.Target)) {
  2337. // throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
  2338. //}
  2339. if (pv.Target != this) {
  2340. nEdges.Add ((pv.Target, from));
  2341. }
  2342. return;
  2343. case Pos.PosCombine pc:
  2344. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  2345. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  2346. break;
  2347. }
  2348. }
  2349. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2350. {
  2351. switch (dim) {
  2352. case Dim.DimView dv:
  2353. // See #2461
  2354. //if (!from.InternalSubviews.Contains (dv.Target)) {
  2355. // throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
  2356. //}
  2357. if (dv.Target != this) {
  2358. nEdges.Add ((dv.Target, from));
  2359. }
  2360. return;
  2361. case Dim.DimCombine dc:
  2362. CollectDim (dc.left, from, ref nNodes, ref nEdges);
  2363. CollectDim (dc.right, from, ref nNodes, ref nEdges);
  2364. break;
  2365. }
  2366. }
  2367. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2368. {
  2369. foreach (var v in from.InternalSubviews) {
  2370. nNodes.Add (v);
  2371. if (v._layoutStyle != LayoutStyle.Computed) {
  2372. continue;
  2373. }
  2374. CollectPos (v.X, v, ref nNodes, ref nEdges);
  2375. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  2376. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  2377. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  2378. }
  2379. }
  2380. // https://en.wikipedia.org/wiki/Topological_sorting
  2381. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  2382. {
  2383. var result = new List<View> ();
  2384. // Set of all nodes with no incoming edges
  2385. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  2386. while (noEdgeNodes.Any ()) {
  2387. // remove a node n from S
  2388. var n = noEdgeNodes.First ();
  2389. noEdgeNodes.Remove (n);
  2390. // add n to tail of L
  2391. if (n != superView)
  2392. result.Add (n);
  2393. // for each node m with an edge e from n to m do
  2394. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  2395. var m = e.To;
  2396. // remove edge e from the graph
  2397. edges.Remove (e);
  2398. // if m has no other incoming edges then
  2399. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  2400. // insert m into S
  2401. noEdgeNodes.Add (m);
  2402. }
  2403. }
  2404. }
  2405. if (edges.Any ()) {
  2406. foreach ((var from, var to) in edges) {
  2407. if (from == to) {
  2408. // if not yet added to the result, add it and remove from edge
  2409. if (result.Find (v => v == from) == null) {
  2410. result.Add (from);
  2411. }
  2412. edges.Remove ((from, to));
  2413. } else if (from.SuperView == to.SuperView) {
  2414. // if 'from' is not yet added to the result, add it
  2415. if (result.Find (v => v == from) == null) {
  2416. result.Add (from);
  2417. }
  2418. // if 'to' is not yet added to the result, add it
  2419. if (result.Find (v => v == to) == null) {
  2420. result.Add (to);
  2421. }
  2422. // remove from edge
  2423. edges.Remove ((from, to));
  2424. } else if (from != superView?.GetTopSuperView (to, from) && !ReferenceEquals (from, to)) {
  2425. if (ReferenceEquals (from.SuperView, to)) {
  2426. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
  2427. } else {
  2428. throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
  2429. }
  2430. }
  2431. }
  2432. }
  2433. // return L (a topologically sorted order)
  2434. return result;
  2435. } // TopologicalSort
  2436. /// <summary>
  2437. /// Overriden by <see cref="Frame"/> to do nothing, as the <see cref="Frame"/> does not have frames.
  2438. /// </summary>
  2439. internal virtual void LayoutFrames ()
  2440. {
  2441. if (Margin == null) return; // CreateFrames() has not been called yet
  2442. if (Margin.Frame.Size != Frame.Size) {
  2443. Margin._frame = new Rect (Point.Empty, Frame.Size);
  2444. Margin.X = 0;
  2445. Margin.Y = 0;
  2446. Margin.Width = Frame.Size.Width;
  2447. Margin.Height = Frame.Size.Height;
  2448. Margin.SetNeedsLayout ();
  2449. Margin.LayoutSubviews ();
  2450. Margin.SetNeedsDisplay ();
  2451. }
  2452. var border = Margin.Thickness.GetInside (Margin.Frame);
  2453. if (border != Border.Frame) {
  2454. Border._frame = new Rect (new Point (border.Location.X, border.Location.Y), border.Size);
  2455. Border.X = border.Location.X;
  2456. Border.Y = border.Location.Y;
  2457. Border.Width = border.Size.Width;
  2458. Border.Height = border.Size.Height;
  2459. Border.SetNeedsLayout ();
  2460. Border.LayoutSubviews ();
  2461. Border.SetNeedsDisplay ();
  2462. }
  2463. var padding = Border.Thickness.GetInside (Border.Frame);
  2464. if (padding != Padding.Frame) {
  2465. Padding._frame = new Rect (new Point (padding.Location.X, padding.Location.Y), padding.Size);
  2466. Padding.X = padding.Location.X;
  2467. Padding.Y = padding.Location.Y;
  2468. Padding.Width = padding.Size.Width;
  2469. Padding.Height = padding.Size.Height;
  2470. Padding.SetNeedsLayout ();
  2471. Padding.LayoutSubviews ();
  2472. Padding.SetNeedsDisplay ();
  2473. }
  2474. }
  2475. /// <summary>
  2476. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  2477. /// response to the container view or terminal resizing.
  2478. /// </summary>
  2479. /// <remarks>
  2480. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  2481. /// </remarks>
  2482. public virtual void LayoutSubviews ()
  2483. {
  2484. if (!LayoutNeeded) {
  2485. return;
  2486. }
  2487. LayoutFrames ();
  2488. var oldBounds = Bounds;
  2489. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  2490. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2491. // Sort out the dependencies of the X, Y, Width, Height properties
  2492. var nodes = new HashSet<View> ();
  2493. var edges = new HashSet<(View, View)> ();
  2494. CollectAll (this, ref nodes, ref edges);
  2495. var ordered = View.TopologicalSort (SuperView, nodes, edges);
  2496. foreach (var v in ordered) {
  2497. LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
  2498. }
  2499. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  2500. // Use LayoutSubview with the Frame of the 'from'
  2501. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded && edges.Count > 0) {
  2502. foreach ((var from, var to) in edges) {
  2503. LayoutSubview (to, from.Frame);
  2504. }
  2505. }
  2506. LayoutNeeded = false;
  2507. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  2508. }
  2509. private void LayoutSubview (View v, Rect contentArea)
  2510. {
  2511. if (v.LayoutStyle == LayoutStyle.Computed) {
  2512. v.SetRelativeLayout (contentArea);
  2513. }
  2514. v.LayoutSubviews ();
  2515. v.LayoutNeeded = false;
  2516. }
  2517. ustring _text;
  2518. /// <summary>
  2519. /// The text displayed by the <see cref="View"/>.
  2520. /// </summary>
  2521. /// <remarks>
  2522. /// <para>
  2523. /// The text will be drawn before any subviews are drawn.
  2524. /// </para>
  2525. /// <para>
  2526. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  2527. /// to <see cref="TextAlignment"/> and <see cref="TextDirection"/>.
  2528. /// </para>
  2529. /// <para>
  2530. /// The text will word-wrap to additional lines if it does not fit horizontally. If <see cref="Bounds"/>'s height
  2531. /// is 1, the text will be clipped.
  2532. /// </para>
  2533. /// <para>
  2534. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  2535. /// <c>(Rune)0xffff</c>.
  2536. /// </para>
  2537. /// </remarks>
  2538. public virtual ustring Text {
  2539. get => _text;
  2540. set {
  2541. _text = value;
  2542. SetHotKey ();
  2543. UpdateTextFormatterText ();
  2544. //TextFormatter.Format ();
  2545. OnResizeNeeded ();
  2546. #if DEBUG
  2547. if (_text != null && string.IsNullOrEmpty (Id)) {
  2548. Id = _text.ToString ();
  2549. }
  2550. #endif
  2551. }
  2552. }
  2553. /// <summary>
  2554. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>
  2555. /// within <see cref="Bounds"/>
  2556. /// <para>
  2557. /// The default is <see langword="false"/>. Set to <see langword="true"/> to turn on AutoSize. If <see langword="true"/> then
  2558. /// <see cref="Width"/> and <see cref="Height"/> will be used if <see cref="Text"/> can fit;
  2559. /// if <see cref="Text"/> won't fit the view will be resized as needed.
  2560. /// </para>
  2561. /// <para>
  2562. /// In addition, if <see cref="ForceValidatePosDim"/> is <see langword="true"/> the new values of <see cref="Width"/> and
  2563. /// <see cref="Height"/> must be of the same types of the existing one to avoid breaking the <see cref="Dim"/> settings.
  2564. /// </para>
  2565. /// </summary>
  2566. public virtual bool AutoSize {
  2567. get => _autoSize;
  2568. set {
  2569. var v = ResizeView (value);
  2570. TextFormatter.AutoSize = v;
  2571. if (_autoSize != v) {
  2572. _autoSize = v;
  2573. TextFormatter.NeedsFormat = true;
  2574. UpdateTextFormatterText ();
  2575. OnResizeNeeded ();
  2576. }
  2577. }
  2578. }
  2579. /// <summary>
  2580. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved
  2581. /// or not when <see cref="TextFormatter.WordWrap"/> is enabled.
  2582. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be removed when
  2583. /// <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  2584. /// </summary>
  2585. public virtual bool PreserveTrailingSpaces {
  2586. get => TextFormatter.PreserveTrailingSpaces;
  2587. set {
  2588. if (TextFormatter.PreserveTrailingSpaces != value) {
  2589. TextFormatter.PreserveTrailingSpaces = value;
  2590. TextFormatter.NeedsFormat = true;
  2591. }
  2592. }
  2593. }
  2594. /// <summary>
  2595. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  2596. /// </summary>
  2597. /// <value>The text alignment.</value>
  2598. public virtual TextAlignment TextAlignment {
  2599. get => TextFormatter.Alignment;
  2600. set {
  2601. TextFormatter.Alignment = value;
  2602. UpdateTextFormatterText ();
  2603. OnResizeNeeded ();
  2604. }
  2605. }
  2606. /// <summary>
  2607. /// Gets or sets how the View's <see cref="Text"/> is aligned vertically when drawn. Changing this property will redisplay the <see cref="View"/>.
  2608. /// </summary>
  2609. /// <value>The text alignment.</value>
  2610. public virtual VerticalTextAlignment VerticalTextAlignment {
  2611. get => TextFormatter.VerticalAlignment;
  2612. set {
  2613. TextFormatter.VerticalAlignment = value;
  2614. SetNeedsDisplay ();
  2615. }
  2616. }
  2617. /// <summary>
  2618. /// Gets or sets the direction of the View's <see cref="Text"/>. Changing this property will redisplay the <see cref="View"/>.
  2619. /// </summary>
  2620. /// <value>The text alignment.</value>
  2621. public virtual TextDirection TextDirection {
  2622. get => TextFormatter.Direction;
  2623. set {
  2624. UpdateTextDirection (value);
  2625. TextFormatter.Direction = value;
  2626. }
  2627. }
  2628. private void UpdateTextDirection (TextDirection newDirection)
  2629. {
  2630. var directionChanged = TextFormatter.IsHorizontalDirection (TextFormatter.Direction)
  2631. != TextFormatter.IsHorizontalDirection (newDirection);
  2632. TextFormatter.Direction = newDirection;
  2633. var isValidOldAutoSize = AutoSize && IsValidAutoSize (out var _);
  2634. UpdateTextFormatterText ();
  2635. if ((!ForceValidatePosDim && directionChanged && AutoSize)
  2636. || (ForceValidatePosDim && directionChanged && AutoSize && isValidOldAutoSize)) {
  2637. OnResizeNeeded ();
  2638. } else if (directionChanged && IsAdded) {
  2639. SetWidthHeight (Bounds.Size);
  2640. SetMinWidthHeight ();
  2641. } else {
  2642. SetMinWidthHeight ();
  2643. }
  2644. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2645. SetNeedsDisplay ();
  2646. }
  2647. /// <summary>
  2648. /// Get or sets if the <see cref="View"/> has been initialized (via <see cref="ISupportInitialize.BeginInit"/>
  2649. /// and <see cref="ISupportInitialize.EndInit"/>).
  2650. /// </summary>
  2651. /// <para>
  2652. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification.IsInitialized"/>
  2653. /// can be implemented, in which case the <see cref="ISupportInitialize"/>
  2654. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  2655. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  2656. /// to override base class layout code optimally by doing so only on first run,
  2657. /// instead of on every run.
  2658. /// </para>
  2659. public virtual bool IsInitialized { get; set; }
  2660. /// <summary>
  2661. /// Gets information if the view was already added to the <see cref="SuperView"/>.
  2662. /// </summary>
  2663. public bool IsAdded { get; private set; }
  2664. bool _oldEnabled;
  2665. /// <inheritdoc/>
  2666. public override bool Enabled {
  2667. get => base.Enabled;
  2668. set {
  2669. if (base.Enabled != value) {
  2670. if (value) {
  2671. if (SuperView == null || SuperView?.Enabled == true) {
  2672. base.Enabled = value;
  2673. }
  2674. } else {
  2675. base.Enabled = value;
  2676. }
  2677. if (!value && HasFocus) {
  2678. SetHasFocus (false, this);
  2679. }
  2680. OnEnabledChanged ();
  2681. SetNeedsDisplay ();
  2682. if (_subviews != null) {
  2683. foreach (var view in _subviews) {
  2684. if (!value) {
  2685. view._oldEnabled = view.Enabled;
  2686. view.Enabled = false;
  2687. } else {
  2688. view.Enabled = view._oldEnabled;
  2689. view._addingView = false;
  2690. }
  2691. }
  2692. }
  2693. }
  2694. }
  2695. }
  2696. /// <summary>
  2697. /// Gets or sets whether a view is cleared if the <see cref="Visible"/> property is <see langword="false"/>.
  2698. /// </summary>
  2699. public bool ClearOnVisibleFalse { get; set; } = true;
  2700. /// <inheritdoc/>>
  2701. public override bool Visible {
  2702. get => base.Visible;
  2703. set {
  2704. if (base.Visible != value) {
  2705. base.Visible = value;
  2706. if (!value) {
  2707. if (HasFocus) {
  2708. SetHasFocus (false, this);
  2709. }
  2710. if (ClearOnVisibleFalse) {
  2711. Clear ();
  2712. }
  2713. }
  2714. OnVisibleChanged ();
  2715. SetNeedsDisplay ();
  2716. }
  2717. }
  2718. }
  2719. /// <summary>
  2720. /// Gets or sets whether the view has a one row/col thick border.
  2721. /// </summary>
  2722. /// <remarks>
  2723. /// <para>
  2724. /// This is a helper for manipulating the view's <see cref="Border"/>. Setting this property to any value other than
  2725. /// <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s <see cref="Frame.Thickness"/>
  2726. /// to `1` and <see cref="BorderStyle"/> to the value.
  2727. /// </para>
  2728. /// <para>
  2729. /// Setting this property to <see cref="LineStyle.None"/> is equivalent to setting <see cref="Border"/>'s <see cref="Frame.Thickness"/>
  2730. /// to `0` and <see cref="BorderStyle"/> to <see cref="LineStyle.None"/>.
  2731. /// </para>
  2732. /// <para>
  2733. /// For more advanced customization of the view's border, manipulate see <see cref="Border"/> directly.
  2734. /// </para>
  2735. /// </remarks>
  2736. public LineStyle BorderStyle {
  2737. get {
  2738. return Border?.BorderStyle ?? LineStyle.None;
  2739. }
  2740. set {
  2741. if (Border == null) {
  2742. throw new InvalidOperationException ("Border is null; this is likely a bug.");
  2743. }
  2744. if (value != LineStyle.None) {
  2745. Border.Thickness = new Thickness (1);
  2746. } else {
  2747. Border.Thickness = new Thickness (0);
  2748. }
  2749. Border.BorderStyle = value;
  2750. LayoutFrames ();
  2751. SetNeedsLayout ();
  2752. }
  2753. }
  2754. /// <summary>
  2755. /// Pretty prints the View
  2756. /// </summary>
  2757. /// <returns></returns>
  2758. public override string ToString ()
  2759. {
  2760. return $"{GetType ().Name}({Id})({Frame})";
  2761. }
  2762. void SetHotKey ()
  2763. {
  2764. if (TextFormatter == null) {
  2765. return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
  2766. }
  2767. TextFormatter.FindHotKey (_text, HotKeySpecifier, true, out _, out var hk);
  2768. if (_hotKey != hk) {
  2769. HotKey = hk;
  2770. }
  2771. }
  2772. bool ResizeView (bool autoSize)
  2773. {
  2774. if (!autoSize) {
  2775. return false;
  2776. }
  2777. var aSize = true;
  2778. var nBoundsSize = GetAutoSize ();
  2779. if (nBoundsSize != Bounds.Size) {
  2780. if (ForceValidatePosDim) {
  2781. aSize = SetWidthHeight (nBoundsSize);
  2782. } else {
  2783. Height = nBoundsSize.Height;
  2784. Width = nBoundsSize.Width; // = new Rect (Bounds.X, Bounds.Y, nBoundsSize.Width, nBoundsSize.Height);
  2785. }
  2786. }
  2787. // BUGBUG: This call may be redundant
  2788. TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
  2789. return aSize;
  2790. }
  2791. /// <summary>
  2792. /// Resizes the View to fit the specified <see cref="Bounds"/> size.
  2793. /// </summary>
  2794. /// <param name="nBounds"></param>
  2795. /// <returns></returns>
  2796. bool SetWidthHeight (Size nBounds)
  2797. {
  2798. var aSize = false;
  2799. var canSizeW = TrySetWidth (nBounds.Width - GetHotKeySpecifierLength (), out var rW);
  2800. var canSizeH = TrySetHeight (nBounds.Height - GetHotKeySpecifierLength (false), out var rH);
  2801. if (canSizeW) {
  2802. aSize = true;
  2803. _width = rW;
  2804. }
  2805. if (canSizeH) {
  2806. aSize = true;
  2807. _height = rH;
  2808. }
  2809. if (aSize) {
  2810. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  2811. }
  2812. return aSize;
  2813. }
  2814. /// <summary>
  2815. /// Gets the Frame dimensions required to fit <see cref="Text"/> using the text <see cref="Direction"/> specified by the
  2816. /// <see cref="TextFormatter"/> property and accounting for any <see cref="HotKeySpecifier"/> characters.
  2817. /// </summary>
  2818. /// <returns>The <see cref="Size"/> required to fit the text.</returns>
  2819. public Size GetAutoSize ()
  2820. {
  2821. var rect = TextFormatter.CalcRect (Bounds.X, Bounds.Y, TextFormatter.Text, TextFormatter.Direction);
  2822. var newWidth = rect.Size.Width - GetHotKeySpecifierLength () + Margin.Thickness.Horizontal + Border.Thickness.Horizontal + Padding.Thickness.Horizontal;
  2823. var newHeight = rect.Size.Height - GetHotKeySpecifierLength (false) + Margin.Thickness.Vertical + Border.Thickness.Vertical + Padding.Thickness.Vertical;
  2824. return new Size (newWidth, newHeight);
  2825. }
  2826. bool IsValidAutoSize (out Size autoSize)
  2827. {
  2828. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  2829. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2830. rect.Size.Height - GetHotKeySpecifierLength (false));
  2831. return !(ForceValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  2832. || _frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  2833. || _frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  2834. }
  2835. bool IsValidAutoSizeWidth (Dim width)
  2836. {
  2837. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  2838. var dimValue = width.Anchor (0);
  2839. return !(ForceValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
  2840. - GetHotKeySpecifierLength ());
  2841. }
  2842. bool IsValidAutoSizeHeight (Dim height)
  2843. {
  2844. var rect = TextFormatter.CalcRect (_frame.X, _frame.Y, TextFormatter.Text, TextDirection);
  2845. var dimValue = height.Anchor (0);
  2846. return !(ForceValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
  2847. - GetHotKeySpecifierLength (false));
  2848. }
  2849. /// <summary>
  2850. /// Gets the width or height of the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> characters
  2851. /// in the <see cref="Text"/> property.
  2852. /// </summary>
  2853. /// <remarks>
  2854. /// Only the first hotkey specifier found in <see cref="Text"/> is supported.
  2855. /// </remarks>
  2856. /// <param name="isWidth">If <see langword="true"/> (the default) the width required for the hotkey specifier is returned. Otherwise the height is returned.</param>
  2857. /// <returns>The number of characters required for the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>. If the text direction specified
  2858. /// by <see cref="TextDirection"/> does not match the <paramref name="isWidth"/> parameter, <c>0</c> is returned.</returns>
  2859. public int GetHotKeySpecifierLength (bool isWidth = true)
  2860. {
  2861. if (isWidth) {
  2862. return TextFormatter.IsHorizontalDirection (TextDirection) &&
  2863. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2864. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2865. } else {
  2866. return TextFormatter.IsVerticalDirection (TextDirection) &&
  2867. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2868. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2869. }
  2870. }
  2871. /// <summary>
  2872. /// Gets the dimensions required for <see cref="Text"/> ignoring a <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>.
  2873. /// </summary>
  2874. /// <returns></returns>
  2875. public Size GetSizeNeededForTextWithoutHotKey ()
  2876. {
  2877. return new Size (TextFormatter.Size.Width - GetHotKeySpecifierLength (),
  2878. TextFormatter.Size.Height - GetHotKeySpecifierLength (false));
  2879. }
  2880. /// <summary>
  2881. /// Gets the dimensions required for <see cref="Text"/> accounting for a <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> .
  2882. /// </summary>
  2883. /// <returns></returns>
  2884. public Size GetSizeNeededForTextAndHotKey ()
  2885. {
  2886. if (ustring.IsNullOrEmpty (TextFormatter.Text)) {
  2887. if (!IsInitialized) return Size.Empty;
  2888. return Bounds.Size;
  2889. }
  2890. // BUGBUG: This IGNORES what Text is set to, using on only the current View size. This doesn't seem to make sense.
  2891. // BUGBUG: This uses Frame; in v2 it should be Bounds
  2892. return new Size (_frame.Size.Width + GetHotKeySpecifierLength (),
  2893. _frame.Size.Height + GetHotKeySpecifierLength (false));
  2894. }
  2895. /// <inheritdoc/>
  2896. public override bool OnMouseEnter (MouseEvent mouseEvent)
  2897. {
  2898. if (!Enabled) {
  2899. return true;
  2900. }
  2901. if (!CanBeVisible (this)) {
  2902. return false;
  2903. }
  2904. var args = new MouseEventEventArgs (mouseEvent);
  2905. MouseEnter?.Invoke (this, args);
  2906. return args.Handled || base.OnMouseEnter (mouseEvent);
  2907. }
  2908. /// <inheritdoc/>
  2909. public override bool OnMouseLeave (MouseEvent mouseEvent)
  2910. {
  2911. if (!Enabled) {
  2912. return true;
  2913. }
  2914. if (!CanBeVisible (this)) {
  2915. return false;
  2916. }
  2917. var args = new MouseEventEventArgs (mouseEvent);
  2918. MouseLeave?.Invoke (this, args);
  2919. return args.Handled || base.OnMouseLeave (mouseEvent);
  2920. }
  2921. /// <summary>
  2922. /// Method invoked when a mouse event is generated
  2923. /// </summary>
  2924. /// <param name="mouseEvent"></param>
  2925. /// <returns><see langword="true"/>, if the event was handled, <see langword="false"/> otherwise.</returns>
  2926. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  2927. {
  2928. if (!Enabled) {
  2929. return true;
  2930. }
  2931. if (!CanBeVisible (this)) {
  2932. return false;
  2933. }
  2934. var args = new MouseEventEventArgs (mouseEvent);
  2935. if (OnMouseClick (args))
  2936. return true;
  2937. if (MouseEvent (mouseEvent))
  2938. return true;
  2939. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  2940. if (CanFocus && !HasFocus && SuperView != null) {
  2941. SuperView.SetFocus (this);
  2942. SetNeedsDisplay ();
  2943. }
  2944. return true;
  2945. }
  2946. return false;
  2947. }
  2948. /// <summary>
  2949. /// Invokes the MouseClick event.
  2950. /// </summary>
  2951. protected bool OnMouseClick (MouseEventEventArgs args)
  2952. {
  2953. if (!Enabled) {
  2954. return true;
  2955. }
  2956. MouseClick?.Invoke (this, args);
  2957. return args.Handled;
  2958. }
  2959. /// <inheritdoc/>
  2960. public override void OnCanFocusChanged () => CanFocusChanged?.Invoke (this, EventArgs.Empty);
  2961. /// <inheritdoc/>
  2962. public override void OnEnabledChanged () => EnabledChanged?.Invoke (this, EventArgs.Empty);
  2963. /// <inheritdoc/>
  2964. public override void OnVisibleChanged () => VisibleChanged?.Invoke (this, EventArgs.Empty);
  2965. /// <inheritdoc/>
  2966. protected override void Dispose (bool disposing)
  2967. {
  2968. Margin?.Dispose ();
  2969. Margin = null;
  2970. Border?.Dispose ();
  2971. Border = null;
  2972. Padding?.Dispose ();
  2973. Padding = null;
  2974. for (var i = InternalSubviews.Count - 1; i >= 0; i--) {
  2975. var subview = InternalSubviews [i];
  2976. Remove (subview);
  2977. subview.Dispose ();
  2978. }
  2979. base.Dispose (disposing);
  2980. }
  2981. /// <summary>
  2982. /// Signals the View that initialization is starting. See <see cref="ISupportInitialize"/>.
  2983. /// </summary>
  2984. /// <remarks>
  2985. /// <para>
  2986. /// Views can opt-in to more sophisticated initialization
  2987. /// by implementing overrides to <see cref="ISupportInitialize.BeginInit"/> and
  2988. /// <see cref="ISupportInitialize.EndInit"/> which will be called
  2989. /// when the view is added to a <see cref="SuperView"/>.
  2990. /// </para>
  2991. /// <para>
  2992. /// If first-run-only initialization is preferred, overrides to <see cref="ISupportInitializeNotification"/>
  2993. /// can be implemented too, in which case the <see cref="ISupportInitialize"/>
  2994. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  2995. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  2996. /// to override base class layout code optimally by doing so only on first run,
  2997. /// instead of on every run.
  2998. /// </para>
  2999. /// </remarks>
  3000. public virtual void BeginInit ()
  3001. {
  3002. if (!IsInitialized) {
  3003. _oldCanFocus = CanFocus;
  3004. _oldTabIndex = _tabIndex;
  3005. UpdateTextDirection (TextDirection);
  3006. UpdateTextFormatterText ();
  3007. SetHotKey ();
  3008. // TODO: Figure out why ScrollView and other tests fail if this call is put here
  3009. // instead of the constructor.
  3010. //InitializeFrames ();
  3011. } else {
  3012. //throw new InvalidOperationException ("The view is already initialized.");
  3013. }
  3014. if (_subviews?.Count > 0) {
  3015. foreach (var view in _subviews) {
  3016. if (!view.IsInitialized) {
  3017. view.BeginInit ();
  3018. }
  3019. }
  3020. }
  3021. }
  3022. /// <summary>
  3023. /// Signals the View that initialization is ending. See <see cref="ISupportInitialize"/>.
  3024. /// </summary>
  3025. public void EndInit ()
  3026. {
  3027. IsInitialized = true;
  3028. OnResizeNeeded ();
  3029. if (_subviews != null) {
  3030. foreach (var view in _subviews) {
  3031. if (!view.IsInitialized) {
  3032. view.EndInit ();
  3033. }
  3034. }
  3035. }
  3036. Initialized?.Invoke (this, EventArgs.Empty);
  3037. }
  3038. bool CanBeVisible (View view)
  3039. {
  3040. if (!view.Visible) {
  3041. return false;
  3042. }
  3043. for (var c = view.SuperView; c != null; c = c.SuperView) {
  3044. if (!c.Visible) {
  3045. return false;
  3046. }
  3047. }
  3048. return true;
  3049. }
  3050. /// <summary>
  3051. /// Determines if the View's <see cref="Width"/> can be set to a new value.
  3052. /// </summary>
  3053. /// <param name="desiredWidth"></param>
  3054. /// <param name="resultWidth">Contains the width that would result if <see cref="Width"/> were set to <paramref name="desiredWidth"/>"/> </param>
  3055. /// <returns><see langword="true"/> if the View's <see cref="Width"/> can be changed to the specified value. False otherwise.</returns>
  3056. internal bool TrySetWidth (int desiredWidth, out int resultWidth)
  3057. {
  3058. var w = desiredWidth;
  3059. bool canSetWidth;
  3060. switch (Width) {
  3061. case Dim.DimCombine _:
  3062. case Dim.DimView _:
  3063. case Dim.DimFill _:
  3064. // It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
  3065. w = Width.Anchor (w);
  3066. canSetWidth = !ForceValidatePosDim;
  3067. break;
  3068. case Dim.DimFactor factor:
  3069. // Tries to get the SuperView Width otherwise the view Width.
  3070. var sw = SuperView != null ? SuperView.Frame.Width : w;
  3071. if (factor.IsFromRemaining ()) {
  3072. sw -= Frame.X;
  3073. }
  3074. w = Width.Anchor (sw);
  3075. canSetWidth = !ForceValidatePosDim;
  3076. break;
  3077. default:
  3078. canSetWidth = true;
  3079. break;
  3080. }
  3081. resultWidth = w;
  3082. return canSetWidth;
  3083. }
  3084. /// <summary>
  3085. /// Determines if the View's <see cref="Height"/> can be set to a new value.
  3086. /// </summary>
  3087. /// <param name="desiredHeight"></param>
  3088. /// <param name="resultHeight">Contains the width that would result if <see cref="Height"/> were set to <paramref name="desiredHeight"/>"/> </param>
  3089. /// <returns><see langword="true"/> if the View's <see cref="Height"/> can be changed to the specified value. False otherwise.</returns>
  3090. internal bool TrySetHeight (int desiredHeight, out int resultHeight)
  3091. {
  3092. var h = desiredHeight;
  3093. bool canSetHeight;
  3094. switch (Height) {
  3095. case Dim.DimCombine _:
  3096. case Dim.DimView _:
  3097. case Dim.DimFill _:
  3098. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  3099. h = Height.Anchor (h);
  3100. canSetHeight = !ForceValidatePosDim;
  3101. break;
  3102. case Dim.DimFactor factor:
  3103. // Tries to get the SuperView height otherwise the view height.
  3104. var sh = SuperView != null ? SuperView.Frame.Height : h;
  3105. if (factor.IsFromRemaining ()) {
  3106. sh -= Frame.Y;
  3107. }
  3108. h = Height.Anchor (sh);
  3109. canSetHeight = !ForceValidatePosDim;
  3110. break;
  3111. default:
  3112. canSetHeight = true;
  3113. break;
  3114. }
  3115. resultHeight = h;
  3116. return canSetHeight;
  3117. }
  3118. /// <summary>
  3119. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3120. /// </summary>
  3121. /// <returns><see cref="Terminal.Gui.ColorScheme.Normal"/> if <see cref="Enabled"/> is <see langword="true"/>
  3122. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3123. /// If it's overridden can return other values.</returns>
  3124. public virtual Attribute GetNormalColor ()
  3125. {
  3126. return Enabled ? ColorScheme.Normal : ColorScheme.Disabled;
  3127. }
  3128. /// <summary>
  3129. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3130. /// </summary>
  3131. /// <returns><see cref="Terminal.Gui.ColorScheme.Focus"/> if <see cref="Enabled"/> is <see langword="true"/>
  3132. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3133. /// If it's overridden can return other values.</returns>
  3134. public virtual Attribute GetFocusColor ()
  3135. {
  3136. return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  3137. }
  3138. /// <summary>
  3139. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  3140. /// </summary>
  3141. /// <returns><see cref="Terminal.Gui.ColorScheme.HotNormal"/> if <see cref="Enabled"/> is <see langword="true"/>
  3142. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  3143. /// If it's overridden can return other values.</returns>
  3144. public virtual Attribute GetHotNormalColor ()
  3145. {
  3146. return Enabled ? ColorScheme.HotNormal : ColorScheme.Disabled;
  3147. }
  3148. /// <summary>
  3149. /// Get the top superview of a given <see cref="View"/>.
  3150. /// </summary>
  3151. /// <returns>The superview view.</returns>
  3152. public View GetTopSuperView (View view = null, View superview = null)
  3153. {
  3154. View top = superview ?? Application.Top;
  3155. for (var v = view?.SuperView ?? (this?.SuperView); v != null; v = v.SuperView) {
  3156. top = v;
  3157. if (top == superview) {
  3158. break;
  3159. }
  3160. }
  3161. return top;
  3162. }
  3163. /// <summary>
  3164. /// Finds which view that belong to the <paramref name="start"/> superview at the provided location.
  3165. /// </summary>
  3166. /// <param name="start">The superview where to look for.</param>
  3167. /// <param name="x">The column location in the superview.</param>
  3168. /// <param name="y">The row location in the superview.</param>
  3169. /// <param name="resx">The found view screen relative column location.</param>
  3170. /// <param name="resy">The found view screen relative row location.</param>
  3171. /// <returns>
  3172. /// The view that was found at the <praramref name="x"/> and <praramref name="y"/> coordinates.
  3173. /// <see langword="null"/> if no view was found.
  3174. /// </returns>
  3175. public static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  3176. {
  3177. var startFrame = start.Frame;
  3178. if (!startFrame.Contains (x, y)) {
  3179. resx = 0;
  3180. resy = 0;
  3181. return null;
  3182. }
  3183. if (start.InternalSubviews != null) {
  3184. int count = start.InternalSubviews.Count;
  3185. if (count > 0) {
  3186. var boundsOffset = start.GetBoundsOffset ();
  3187. var rx = x - (startFrame.X + boundsOffset.X);
  3188. var ry = y - (startFrame.Y + boundsOffset.Y);
  3189. for (int i = count - 1; i >= 0; i--) {
  3190. View v = start.InternalSubviews [i];
  3191. if (v.Visible && v.Frame.Contains (rx, ry)) {
  3192. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  3193. if (deep == null)
  3194. return v;
  3195. return deep;
  3196. }
  3197. }
  3198. }
  3199. }
  3200. resx = x - startFrame.X;
  3201. resy = y - startFrame.Y;
  3202. return start;
  3203. }
  3204. }
  3205. }