View.cs 107 KB

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