View.cs 95 KB

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