View.cs 110 KB

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