View.cs 77 KB

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