View.cs 94 KB

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