View.cs 105 KB

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