View.cs 99 KB

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