2
0

View.cs 103 KB

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