View.cs 98 KB

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