View.cs 111 KB

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