View.cs 107 KB

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