View.cs 76 KB

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