View.cs 85 KB

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