View.cs 98 KB

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