View.cs 108 KB

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