View.cs 95 KB

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