View.cs 109 KB

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