View.cs 102 KB

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