View.cs 97 KB

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