2
0

View.cs 100 KB

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