View.cs 109 KB

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