View.cs 100 KB

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