View.cs 110 KB

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