View.cs 109 KB

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