2
0

View.cs 113 KB

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