View.cs 110 KB

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