View.cs 94 KB

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