View.cs 83 KB

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