2
0

View.cs 107 KB

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