View.cs 88 KB

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