View.cs 75 KB

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