View.cs 89 KB

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