View.cs 102 KB

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