View.cs 109 KB

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