View.cs 111 KB

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