View.cs 98 KB

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