View.cs 104 KB

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