View.cs 110 KB

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