View.cs 99 KB

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