View.cs 99 KB

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