View.cs 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176
  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. var h = Frame.Height;
  1000. var w = Frame.Width;
  1001. for (var line = 0; line < h; line++) {
  1002. Move (0, line);
  1003. for (var col = 0; col < w; col++)
  1004. Driver.AddRune (' ');
  1005. }
  1006. }
  1007. /// <summary>
  1008. /// Clears the specified region with the current color.
  1009. /// </summary>
  1010. /// <remarks>
  1011. /// </remarks>
  1012. /// <param name="regionScreen">The screen-relative region to clear.</param>
  1013. public void Clear (Rect regionScreen)
  1014. {
  1015. var h = regionScreen.Height;
  1016. var w = regionScreen.Width;
  1017. for (var line = regionScreen.Y; line < regionScreen.Y + h; line++) {
  1018. Driver.Move (regionScreen.X, line);
  1019. for (var col = 0; col < w; col++)
  1020. Driver.AddRune (' ');
  1021. }
  1022. }
  1023. /// <summary>
  1024. /// Converts a view-relative (col,row) position to a screen-relative position (col,row). The values are optionally clamped to the screen dimensions.
  1025. /// </summary>
  1026. /// <param name="col">View-relative column.</param>
  1027. /// <param name="row">View-relative row.</param>
  1028. /// <param name="rcol">Absolute column; screen-relative.</param>
  1029. /// <param name="rrow">Absolute row; screen-relative.</param>
  1030. /// <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>
  1031. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  1032. {
  1033. // Computes the real row, col relative to the screen.
  1034. rrow = row + frame.Y;
  1035. rcol = col + frame.X;
  1036. var curContainer = container;
  1037. while (curContainer != null) {
  1038. rrow += curContainer.frame.Y;
  1039. rcol += curContainer.frame.X;
  1040. curContainer = curContainer.container;
  1041. }
  1042. // The following ensures that the cursor is always in the screen boundaries.
  1043. if (clipped) {
  1044. rrow = Math.Min (rrow, Driver.Rows - 1);
  1045. rcol = Math.Min (rcol, Driver.Cols - 1);
  1046. }
  1047. }
  1048. /// <summary>
  1049. /// Converts a point from screen-relative coordinates to view-relative coordinates.
  1050. /// </summary>
  1051. /// <returns>The mapped point.</returns>
  1052. /// <param name="x">X screen-coordinate point.</param>
  1053. /// <param name="y">Y screen-coordinate point.</param>
  1054. public Point ScreenToView (int x, int y)
  1055. {
  1056. if (SuperView == null) {
  1057. return new Point (x - Frame.X, y - frame.Y);
  1058. } else {
  1059. var parent = SuperView.ScreenToView (x, y);
  1060. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  1061. }
  1062. }
  1063. /// <summary>
  1064. /// Converts a region in view-relative coordinates to screen-relative coordinates.
  1065. /// </summary>
  1066. internal Rect ViewToScreen (Rect region)
  1067. {
  1068. ViewToScreen (region.X, region.Y, out var x, out var y, clipped: false);
  1069. return new Rect (x, y, region.Width, region.Height);
  1070. }
  1071. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  1072. internal Rect ScreenClip (Rect regionScreen)
  1073. {
  1074. var x = regionScreen.X < 0 ? 0 : regionScreen.X;
  1075. var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
  1076. var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
  1077. var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
  1078. return new Rect (x, y, w, h);
  1079. }
  1080. /// <summary>
  1081. /// Sets the <see cref="ConsoleDriver"/>'s clip region to the current View's <see cref="Bounds"/>.
  1082. /// </summary>
  1083. /// <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>
  1084. /// <remarks>
  1085. /// <see cref="Bounds"/> is View-relative.
  1086. /// </remarks>
  1087. public Rect ClipToBounds ()
  1088. {
  1089. return SetClip (Bounds);
  1090. }
  1091. /// <summary>
  1092. /// Sets the clip region to the specified view-relative region.
  1093. /// </summary>
  1094. /// <returns>The previous screen-relative clip region.</returns>
  1095. /// <param name="region">View-relative clip region.</param>
  1096. public Rect SetClip (Rect region)
  1097. {
  1098. var previous = Driver.Clip;
  1099. Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
  1100. return previous;
  1101. }
  1102. /// <summary>
  1103. /// Draws a frame in the current view, clipped by the boundary of this view
  1104. /// </summary>
  1105. /// <param name="region">View-relative region for the frame to be drawn.</param>
  1106. /// <param name="padding">The padding to add around the outside of the drawn frame.</param>
  1107. /// <param name="fill">If set to <see langword="true"/> it fill will the contents.</param>
  1108. public void DrawFrame (Rect region, int padding = 0, bool fill = false)
  1109. {
  1110. var scrRect = ViewToScreen (region);
  1111. var savedClip = ClipToBounds ();
  1112. Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
  1113. Driver.Clip = savedClip;
  1114. }
  1115. /// <summary>
  1116. /// Utility function to draw strings that contain a hotkey.
  1117. /// </summary>
  1118. /// <param name="text">String to display, the hotkey specifier before a letter flags the next letter as the hotkey.</param>
  1119. /// <param name="hotColor">Hot color.</param>
  1120. /// <param name="normalColor">Normal color.</param>
  1121. /// <remarks>
  1122. /// <para>The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.</para>
  1123. /// <para>The hotkey specifier can be changed via <see cref="HotKeySpecifier"/></para>
  1124. /// </remarks>
  1125. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  1126. {
  1127. var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
  1128. Application.Driver.SetAttribute (normalColor);
  1129. foreach (var rune in text) {
  1130. if (rune == hotkeySpec) {
  1131. Application.Driver.SetAttribute (hotColor);
  1132. continue;
  1133. }
  1134. Application.Driver.AddRune (rune);
  1135. Application.Driver.SetAttribute (normalColor);
  1136. }
  1137. }
  1138. /// <summary>
  1139. /// Utility function to draw strings that contains a hotkey using a <see cref="ColorScheme"/> and the "focused" state.
  1140. /// </summary>
  1141. /// <param name="text">String to display, the underscore before a letter flags the next letter as the hotkey.</param>
  1142. /// <param name="focused">If set to <see langword="true"/> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  1143. /// <param name="scheme">The color scheme to use.</param>
  1144. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  1145. {
  1146. if (focused)
  1147. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  1148. else
  1149. DrawHotString (text, Enabled ? scheme.HotNormal : scheme.Disabled, Enabled ? scheme.Normal : scheme.Disabled);
  1150. }
  1151. /// <summary>
  1152. /// This moves the cursor to the specified column and row in the view.
  1153. /// </summary>
  1154. /// <returns>The move.</returns>
  1155. /// <param name="col">Col.</param>
  1156. /// <param name="row">Row.</param>
  1157. /// <param name="clipped">Whether to clip the result of the ViewToScreen method,
  1158. /// if set to <see langword="true"/>, the col, row values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).</param>
  1159. public void Move (int col, int row, bool clipped = true)
  1160. {
  1161. if (Driver.Rows == 0) {
  1162. return;
  1163. }
  1164. ViewToScreen (col, row, out var rCol, out var rRow, clipped);
  1165. Driver.Move (rCol, rRow);
  1166. }
  1167. /// <summary>
  1168. /// Positions the cursor in the right position based on the currently focused view in the chain.
  1169. /// </summary>
  1170. /// Views that are focusable should override <see cref="PositionCursor"/> to ensure
  1171. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  1172. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  1173. /// the last focused view. Views should make sure that they place the cursor
  1174. /// in a visually sensible place.
  1175. public virtual void PositionCursor ()
  1176. {
  1177. if (!CanBeVisible (this) || !Enabled) {
  1178. return;
  1179. }
  1180. if (focused == null && SuperView != null) {
  1181. SuperView.EnsureFocus ();
  1182. } else if (focused?.Visible == true && focused?.Enabled == true && focused?.Frame.Width > 0 && focused.Frame.Height > 0) {
  1183. focused.PositionCursor ();
  1184. } else if (focused?.Visible == true && focused?.Enabled == false) {
  1185. focused = null;
  1186. } else if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
  1187. Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
  1188. } else {
  1189. Move (frame.X, frame.Y);
  1190. }
  1191. }
  1192. bool hasFocus;
  1193. /// <inheritdoc/>
  1194. public override bool HasFocus => hasFocus;
  1195. void SetHasFocus (bool value, View view, bool force = false)
  1196. {
  1197. if (hasFocus != value || force) {
  1198. hasFocus = value;
  1199. if (value) {
  1200. OnEnter (view);
  1201. } else {
  1202. OnLeave (view);
  1203. }
  1204. SetNeedsDisplay ();
  1205. }
  1206. // Remove focus down the chain of subviews if focus is removed
  1207. if (!value && focused != null) {
  1208. var f = focused;
  1209. f.OnLeave (view);
  1210. f.SetHasFocus (false, view);
  1211. focused = null;
  1212. }
  1213. }
  1214. /// <summary>
  1215. /// Defines the event arguments for <see cref="SetFocus(View)"/>
  1216. /// </summary>
  1217. public class FocusEventArgs : EventArgs {
  1218. /// <summary>
  1219. /// Constructs.
  1220. /// </summary>
  1221. /// <param name="view">The view that gets or loses focus.</param>
  1222. public FocusEventArgs (View view) { View = view; }
  1223. /// <summary>
  1224. /// Indicates if the current focus event has already been processed and the driver should stop notifying any other event subscriber.
  1225. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1226. /// </summary>
  1227. public bool Handled { get; set; }
  1228. /// <summary>
  1229. /// Indicates the current view that gets or loses focus.
  1230. /// </summary>
  1231. public View View { get; set; }
  1232. }
  1233. /// <summary>
  1234. /// Method invoked when a subview is being added to this view.
  1235. /// </summary>
  1236. /// <param name="view">The subview being added.</param>
  1237. public virtual void OnAdded (View view)
  1238. {
  1239. view.IsAdded = true;
  1240. view.x = view.x ?? view.frame.X;
  1241. view.y = view.y ?? view.frame.Y;
  1242. view.width = view.width ?? view.frame.Width;
  1243. view.height = view.height ?? view.frame.Height;
  1244. view.Added?.Invoke (this);
  1245. }
  1246. /// <summary>
  1247. /// Method invoked when a subview is being removed from this view.
  1248. /// </summary>
  1249. /// <param name="view">The subview being removed.</param>
  1250. public virtual void OnRemoved (View view)
  1251. {
  1252. view.IsAdded = false;
  1253. view.Removed?.Invoke (this);
  1254. }
  1255. /// <inheritdoc/>
  1256. public override bool OnEnter (View view)
  1257. {
  1258. var args = new FocusEventArgs (view);
  1259. Enter?.Invoke (args);
  1260. if (args.Handled)
  1261. return true;
  1262. if (base.OnEnter (view))
  1263. return true;
  1264. return false;
  1265. }
  1266. /// <inheritdoc/>
  1267. public override bool OnLeave (View view)
  1268. {
  1269. var args = new FocusEventArgs (view);
  1270. Leave?.Invoke (args);
  1271. if (args.Handled)
  1272. return true;
  1273. if (base.OnLeave (view))
  1274. return true;
  1275. return false;
  1276. }
  1277. /// <summary>
  1278. /// Returns the currently focused view inside this view, or null if nothing is focused.
  1279. /// </summary>
  1280. /// <value>The focused.</value>
  1281. public View Focused => focused;
  1282. /// <summary>
  1283. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  1284. /// </summary>
  1285. /// <value>The most focused View.</value>
  1286. public View MostFocused {
  1287. get {
  1288. if (Focused == null)
  1289. return null;
  1290. var most = Focused.MostFocused;
  1291. if (most != null)
  1292. return most;
  1293. return Focused;
  1294. }
  1295. }
  1296. ColorScheme colorScheme;
  1297. /// <summary>
  1298. /// The color scheme for this view, if it is not defined, it returns the <see cref="SuperView"/>'s
  1299. /// color scheme.
  1300. /// </summary>
  1301. public virtual ColorScheme ColorScheme {
  1302. get {
  1303. if (colorScheme == null) {
  1304. return SuperView?.ColorScheme;
  1305. }
  1306. return colorScheme;
  1307. }
  1308. set {
  1309. if (colorScheme != value) {
  1310. colorScheme = value;
  1311. SetNeedsDisplay ();
  1312. }
  1313. }
  1314. }
  1315. /// <summary>
  1316. /// Displays the specified character in the specified column and row of the View.
  1317. /// </summary>
  1318. /// <param name="col">Column (view-relative).</param>
  1319. /// <param name="row">Row (view-relative).</param>
  1320. /// <param name="ch">Ch.</param>
  1321. public void AddRune (int col, int row, Rune ch)
  1322. {
  1323. if (row < 0 || col < 0)
  1324. return;
  1325. if (row > frame.Height - 1 || col > frame.Width - 1)
  1326. return;
  1327. Move (col, row);
  1328. Driver.AddRune (ch);
  1329. }
  1330. /// <summary>
  1331. /// Removes the <see cref="SetNeedsDisplay()"/> and the <see cref="ChildNeedsDisplay"/> setting on this view.
  1332. /// </summary>
  1333. protected void ClearNeedsDisplay ()
  1334. {
  1335. NeedDisplay = Rect.Empty;
  1336. ChildNeedsDisplay = false;
  1337. }
  1338. /// <summary>
  1339. /// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
  1340. /// </summary>
  1341. /// <param name="bounds">The bounds (view-relative region) to redraw.</param>
  1342. /// <remarks>
  1343. /// <para>
  1344. /// Always use <see cref="Bounds"/> (view-relative) when calling <see cref="Redraw(Rect)"/>, NOT <see cref="Frame"/> (superview-relative).
  1345. /// </para>
  1346. /// <para>
  1347. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  1348. /// the last color that was set globally on the driver.
  1349. /// </para>
  1350. /// <para>
  1351. /// Overrides of <see cref="Redraw"/> must ensure they do not set <c>Driver.Clip</c> to a clip region
  1352. /// larger than the <ref name="bounds"/> parameter, as this will cause the driver to clip the entire region.
  1353. /// </para>
  1354. /// </remarks>
  1355. public virtual void Redraw (Rect bounds)
  1356. {
  1357. if (!CanBeVisible (this)) {
  1358. return;
  1359. }
  1360. var clipRect = new Rect (Point.Empty, frame.Size);
  1361. if (ColorScheme != null) {
  1362. Driver.SetAttribute (HasFocus ? GetFocusColor () : GetNormalColor ());
  1363. }
  1364. if (!IgnoreBorderPropertyOnRedraw && Border != null) {
  1365. Border.DrawContent (this);
  1366. } else if (ustring.IsNullOrEmpty (TextFormatter.Text) &&
  1367. (GetType ().IsNestedPublic && !IsOverridden (this, "Redraw") || GetType ().Name == "View") &&
  1368. (!NeedDisplay.IsEmpty || ChildNeedsDisplay || LayoutNeeded)) {
  1369. Clear ();
  1370. SetChildNeedsDisplay ();
  1371. }
  1372. if (!ustring.IsNullOrEmpty (TextFormatter.Text)) {
  1373. Rect containerBounds = GetContainerBounds ();
  1374. Clear (GetNeedDisplay (containerBounds));
  1375. SetChildNeedsDisplay ();
  1376. // Draw any Text
  1377. if (TextFormatter != null) {
  1378. TextFormatter.NeedsFormat = true;
  1379. }
  1380. TextFormatter?.Draw (ViewToScreen (Bounds), HasFocus ? GetFocusColor () : GetNormalColor (),
  1381. HasFocus ? ColorScheme.HotFocus : GetHotNormalColor (),
  1382. containerBounds);
  1383. }
  1384. // Invoke DrawContentEvent
  1385. OnDrawContent (bounds);
  1386. if (subviews != null) {
  1387. foreach (var view in subviews) {
  1388. if (!view.NeedDisplay.IsEmpty || view.ChildNeedsDisplay || view.LayoutNeeded) {
  1389. if (view.Frame.IntersectsWith (clipRect) && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
  1390. if (view.LayoutNeeded) {
  1391. view.LayoutSubviews ();
  1392. }
  1393. // Draw the subview
  1394. // Use the view's bounds (view-relative; Location will always be (0,0)
  1395. if (view.Visible && view.Frame.Width > 0 && view.Frame.Height > 0) {
  1396. var rect = view.Bounds;
  1397. view.OnDrawContent (rect);
  1398. view.Redraw (rect);
  1399. view.OnDrawContentComplete (rect);
  1400. }
  1401. }
  1402. view.NeedDisplay = Rect.Empty;
  1403. view.ChildNeedsDisplay = false;
  1404. }
  1405. }
  1406. }
  1407. // Invoke DrawContentCompleteEvent
  1408. OnDrawContentComplete (bounds);
  1409. ClearLayoutNeeded ();
  1410. ClearNeedsDisplay ();
  1411. }
  1412. Rect GetNeedDisplay (Rect containerBounds)
  1413. {
  1414. Rect rect = ViewToScreen (NeedDisplay);
  1415. if (!containerBounds.IsEmpty) {
  1416. rect.Width = Math.Min (NeedDisplay.Width, containerBounds.Width);
  1417. rect.Height = Math.Min (NeedDisplay.Height, containerBounds.Height);
  1418. }
  1419. return rect;
  1420. }
  1421. Rect GetContainerBounds ()
  1422. {
  1423. var containerBounds = SuperView == null ? default : SuperView.ViewToScreen (SuperView.Bounds);
  1424. var driverClip = Driver == null ? Rect.Empty : Driver.Clip;
  1425. containerBounds.X = Math.Max (containerBounds.X, driverClip.X);
  1426. containerBounds.Y = Math.Max (containerBounds.Y, driverClip.Y);
  1427. var lenOffset = (driverClip.X + driverClip.Width) - (containerBounds.X + containerBounds.Width);
  1428. if (containerBounds.X + containerBounds.Width > driverClip.X + driverClip.Width) {
  1429. containerBounds.Width = Math.Max (containerBounds.Width + lenOffset, 0);
  1430. } else {
  1431. containerBounds.Width = Math.Min (containerBounds.Width, driverClip.Width);
  1432. }
  1433. lenOffset = (driverClip.Y + driverClip.Height) - (containerBounds.Y + containerBounds.Height);
  1434. if (containerBounds.Y + containerBounds.Height > driverClip.Y + driverClip.Height) {
  1435. containerBounds.Height = Math.Max (containerBounds.Height + lenOffset, 0);
  1436. } else {
  1437. containerBounds.Height = Math.Min (containerBounds.Height, driverClip.Height);
  1438. }
  1439. return containerBounds;
  1440. }
  1441. /// <summary>
  1442. /// Event invoked when the content area of the View is to be drawn.
  1443. /// </summary>
  1444. /// <remarks>
  1445. /// <para>
  1446. /// Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.
  1447. /// </para>
  1448. /// <para>
  1449. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1450. /// </para>
  1451. /// </remarks>
  1452. public event Action<Rect> DrawContent;
  1453. /// <summary>
  1454. /// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
  1455. /// </summary>
  1456. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1457. /// <remarks>
  1458. /// This method will be called before any subviews added with <see cref="Add(View)"/> have been drawn.
  1459. /// </remarks>
  1460. public virtual void OnDrawContent (Rect viewport)
  1461. {
  1462. DrawContent?.Invoke (viewport);
  1463. }
  1464. /// <summary>
  1465. /// Event invoked when the content area of the View is completed drawing.
  1466. /// </summary>
  1467. /// <remarks>
  1468. /// <para>
  1469. /// Will be invoked after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1470. /// </para>
  1471. /// <para>
  1472. /// Rect provides the view-relative rectangle describing the currently visible viewport into the <see cref="View"/>.
  1473. /// </para>
  1474. /// </remarks>
  1475. public event Action<Rect> DrawContentComplete;
  1476. /// <summary>
  1477. /// Enables overrides after completed drawing infinitely scrolled content and/or a background behind removed controls.
  1478. /// </summary>
  1479. /// <param name="viewport">The view-relative rectangle describing the currently visible viewport into the <see cref="View"/></param>
  1480. /// <remarks>
  1481. /// This method will be called after any subviews removed with <see cref="Remove(View)"/> have been completed drawing.
  1482. /// </remarks>
  1483. public virtual void OnDrawContentComplete (Rect viewport)
  1484. {
  1485. DrawContentComplete?.Invoke (viewport);
  1486. }
  1487. /// <summary>
  1488. /// Causes the specified subview to have focus.
  1489. /// </summary>
  1490. /// <param name="view">View.</param>
  1491. void SetFocus (View view)
  1492. {
  1493. if (view == null)
  1494. return;
  1495. //Console.WriteLine ($"Request to focus {view}");
  1496. if (!view.CanFocus || !view.Visible || !view.Enabled)
  1497. return;
  1498. if (focused?.hasFocus == true && focused == view)
  1499. return;
  1500. // Make sure that this view is a subview
  1501. View c;
  1502. for (c = view.container; c != null; c = c.container)
  1503. if (c == this)
  1504. break;
  1505. if (c == null)
  1506. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  1507. if (focused != null)
  1508. focused.SetHasFocus (false, view);
  1509. var f = focused;
  1510. focused = view;
  1511. focused.SetHasFocus (true, f);
  1512. focused.EnsureFocus ();
  1513. // Send focus upwards
  1514. SuperView?.SetFocus (this);
  1515. }
  1516. /// <summary>
  1517. /// Causes the specified view and the entire parent hierarchy to have the focused order updated.
  1518. /// </summary>
  1519. public void SetFocus ()
  1520. {
  1521. if (!CanBeVisible (this) || !Enabled) {
  1522. if (HasFocus) {
  1523. SetHasFocus (false, this);
  1524. }
  1525. return;
  1526. }
  1527. SuperView?.SetFocus (this);
  1528. }
  1529. /// <summary>
  1530. /// Defines the event arguments for <see cref="KeyEvent"/>
  1531. /// </summary>
  1532. public class KeyEventEventArgs : EventArgs {
  1533. /// <summary>
  1534. /// Constructs.
  1535. /// </summary>
  1536. /// <param name="ke"></param>
  1537. public KeyEventEventArgs (KeyEvent ke) => KeyEvent = ke;
  1538. /// <summary>
  1539. /// The <see cref="KeyEvent"/> for the event.
  1540. /// </summary>
  1541. public KeyEvent KeyEvent { get; set; }
  1542. /// <summary>
  1543. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other event subscriber.
  1544. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  1545. /// </summary>
  1546. public bool Handled { get; set; } = false;
  1547. }
  1548. /// <summary>
  1549. /// Invoked when a character key is pressed and occurs after the key up event.
  1550. /// </summary>
  1551. public event Action<KeyEventEventArgs> KeyPress;
  1552. /// <inheritdoc/>
  1553. public override bool ProcessKey (KeyEvent keyEvent)
  1554. {
  1555. if (!Enabled) {
  1556. return false;
  1557. }
  1558. var args = new KeyEventEventArgs (keyEvent);
  1559. KeyPress?.Invoke (args);
  1560. if (args.Handled)
  1561. return true;
  1562. if (Focused?.Enabled == true) {
  1563. Focused?.KeyPress?.Invoke (args);
  1564. if (args.Handled)
  1565. return true;
  1566. }
  1567. return Focused?.Enabled == true && Focused?.ProcessKey (keyEvent) == true;
  1568. }
  1569. /// <summary>
  1570. /// Invokes any binding that is registered on this <see cref="View"/>
  1571. /// and matches the <paramref name="keyEvent"/>
  1572. /// </summary>
  1573. /// <param name="keyEvent">The key event passed.</param>
  1574. protected bool? InvokeKeybindings (KeyEvent keyEvent)
  1575. {
  1576. bool? toReturn = null;
  1577. if (KeyBindings.ContainsKey (keyEvent.Key)) {
  1578. foreach (var command in KeyBindings [keyEvent.Key]) {
  1579. if (!CommandImplementations.ContainsKey (command)) {
  1580. 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})");
  1581. }
  1582. // each command has its own return value
  1583. var thisReturn = CommandImplementations [command] ();
  1584. // if we haven't got anything yet, the current command result should be used
  1585. if (toReturn == null) {
  1586. toReturn = thisReturn;
  1587. }
  1588. // if ever see a true then that's what we will return
  1589. if (thisReturn ?? false) {
  1590. toReturn = true;
  1591. }
  1592. }
  1593. }
  1594. return toReturn;
  1595. }
  1596. /// <summary>
  1597. /// <para>Adds a new key combination that will trigger the given <paramref name="command"/>
  1598. /// (if supported by the View - see <see cref="GetSupportedCommands"/>)
  1599. /// </para>
  1600. /// <para>If the key is already bound to a different <see cref="Command"/> it will be
  1601. /// rebound to this one</para>
  1602. /// <remarks>Commands are only ever applied to the current <see cref="View"/>(i.e. this feature
  1603. /// cannot be used to switch focus to another view and perform multiple commands there) </remarks>
  1604. /// </summary>
  1605. /// <param name="key"></param>
  1606. /// <param name="command">The command(s) to run on the <see cref="View"/> when <paramref name="key"/> is pressed.
  1607. /// When specifying multiple commands, all commands will be applied in sequence. The bound <paramref name="key"/> strike
  1608. /// will be consumed if any took effect.</param>
  1609. public void AddKeyBinding (Key key, params Command [] command)
  1610. {
  1611. if (command.Length == 0) {
  1612. throw new ArgumentException ("At least one command must be specified", nameof (command));
  1613. }
  1614. if (KeyBindings.ContainsKey (key)) {
  1615. KeyBindings [key] = command;
  1616. } else {
  1617. KeyBindings.Add (key, command);
  1618. }
  1619. }
  1620. /// <summary>
  1621. /// Replaces a key combination already bound to <see cref="Command"/>.
  1622. /// </summary>
  1623. /// <param name="fromKey">The key to be replaced.</param>
  1624. /// <param name="toKey">The new key to be used.</param>
  1625. protected void ReplaceKeyBinding (Key fromKey, Key toKey)
  1626. {
  1627. if (KeyBindings.ContainsKey (fromKey)) {
  1628. var value = KeyBindings [fromKey];
  1629. KeyBindings.Remove (fromKey);
  1630. KeyBindings [toKey] = value;
  1631. }
  1632. }
  1633. /// <summary>
  1634. /// Checks if the key binding already exists.
  1635. /// </summary>
  1636. /// <param name="key">The key to check.</param>
  1637. /// <returns><see langword="true"/> If the key already exist, <see langword="false"/> otherwise.</returns>
  1638. public bool ContainsKeyBinding (Key key)
  1639. {
  1640. return KeyBindings.ContainsKey (key);
  1641. }
  1642. /// <summary>
  1643. /// Removes all bound keys from the View and resets the default bindings.
  1644. /// </summary>
  1645. public void ClearKeybindings ()
  1646. {
  1647. KeyBindings.Clear ();
  1648. }
  1649. /// <summary>
  1650. /// Clears the existing keybinding (if any) for the given <paramref name="key"/>.
  1651. /// </summary>
  1652. /// <param name="key"></param>
  1653. public void ClearKeybinding (Key key)
  1654. {
  1655. KeyBindings.Remove (key);
  1656. }
  1657. /// <summary>
  1658. /// Removes all key bindings that trigger the given command. Views can have multiple different
  1659. /// keys bound to the same command and this method will clear all of them.
  1660. /// </summary>
  1661. /// <param name="command"></param>
  1662. public void ClearKeybinding (params Command [] command)
  1663. {
  1664. foreach (var kvp in KeyBindings.Where (kvp => kvp.Value.SequenceEqual (command)).ToArray ()) {
  1665. KeyBindings.Remove (kvp.Key);
  1666. }
  1667. }
  1668. /// <summary>
  1669. /// <para>States that the given <see cref="View"/> supports a given <paramref name="command"/>
  1670. /// and what <paramref name="f"/> to perform to make that command happen
  1671. /// </para>
  1672. /// <para>If the <paramref name="command"/> already has an implementation the <paramref name="f"/>
  1673. /// will replace the old one</para>
  1674. /// </summary>
  1675. /// <param name="command">The command.</param>
  1676. /// <param name="f">The function.</param>
  1677. protected void AddCommand (Command command, Func<bool?> f)
  1678. {
  1679. // if there is already an implementation of this command
  1680. if (CommandImplementations.ContainsKey (command)) {
  1681. // replace that implementation
  1682. CommandImplementations [command] = f;
  1683. } else {
  1684. // else record how to perform the action (this should be the normal case)
  1685. CommandImplementations.Add (command, f);
  1686. }
  1687. }
  1688. /// <summary>
  1689. /// Returns all commands that are supported by this <see cref="View"/>.
  1690. /// </summary>
  1691. /// <returns></returns>
  1692. public IEnumerable<Command> GetSupportedCommands ()
  1693. {
  1694. return CommandImplementations.Keys;
  1695. }
  1696. /// <summary>
  1697. /// Gets the key used by a command.
  1698. /// </summary>
  1699. /// <param name="command">The command to search.</param>
  1700. /// <returns>The <see cref="Key"/> used by a <see cref="Command"/></returns>
  1701. public Key GetKeyFromCommand (params Command [] command)
  1702. {
  1703. return KeyBindings.First (kb => kb.Value.SequenceEqual (command)).Key;
  1704. }
  1705. /// <inheritdoc/>
  1706. public override bool ProcessHotKey (KeyEvent keyEvent)
  1707. {
  1708. if (!Enabled) {
  1709. return false;
  1710. }
  1711. var args = new KeyEventEventArgs (keyEvent);
  1712. if (MostFocused?.Enabled == true) {
  1713. MostFocused?.KeyPress?.Invoke (args);
  1714. if (args.Handled)
  1715. return true;
  1716. }
  1717. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1718. return true;
  1719. if (subviews == null || subviews.Count == 0)
  1720. return false;
  1721. foreach (var view in subviews)
  1722. if (view.Enabled && view.ProcessHotKey (keyEvent))
  1723. return true;
  1724. return false;
  1725. }
  1726. /// <inheritdoc/>
  1727. public override bool ProcessColdKey (KeyEvent keyEvent)
  1728. {
  1729. if (!Enabled) {
  1730. return false;
  1731. }
  1732. var args = new KeyEventEventArgs (keyEvent);
  1733. KeyPress?.Invoke (args);
  1734. if (args.Handled)
  1735. return true;
  1736. if (MostFocused?.Enabled == true) {
  1737. MostFocused?.KeyPress?.Invoke (args);
  1738. if (args.Handled)
  1739. return true;
  1740. }
  1741. if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
  1742. return true;
  1743. if (subviews == null || subviews.Count == 0)
  1744. return false;
  1745. foreach (var view in subviews)
  1746. if (view.Enabled && view.ProcessColdKey (keyEvent))
  1747. return true;
  1748. return false;
  1749. }
  1750. /// <summary>
  1751. /// Invoked when a key is pressed.
  1752. /// </summary>
  1753. public event Action<KeyEventEventArgs> KeyDown;
  1754. /// <inheritdoc/>
  1755. public override bool OnKeyDown (KeyEvent keyEvent)
  1756. {
  1757. if (!Enabled) {
  1758. return false;
  1759. }
  1760. var args = new KeyEventEventArgs (keyEvent);
  1761. KeyDown?.Invoke (args);
  1762. if (args.Handled) {
  1763. return true;
  1764. }
  1765. if (Focused?.Enabled == true) {
  1766. Focused.KeyDown?.Invoke (args);
  1767. if (args.Handled) {
  1768. return true;
  1769. }
  1770. if (Focused?.OnKeyDown (keyEvent) == true) {
  1771. return true;
  1772. }
  1773. }
  1774. return false;
  1775. }
  1776. /// <summary>
  1777. /// Invoked when a key is released.
  1778. /// </summary>
  1779. public event Action<KeyEventEventArgs> KeyUp;
  1780. /// <inheritdoc/>
  1781. public override bool OnKeyUp (KeyEvent keyEvent)
  1782. {
  1783. if (!Enabled) {
  1784. return false;
  1785. }
  1786. var args = new KeyEventEventArgs (keyEvent);
  1787. KeyUp?.Invoke (args);
  1788. if (args.Handled) {
  1789. return true;
  1790. }
  1791. if (Focused?.Enabled == true) {
  1792. Focused.KeyUp?.Invoke (args);
  1793. if (args.Handled) {
  1794. return true;
  1795. }
  1796. if (Focused?.OnKeyUp (keyEvent) == true) {
  1797. return true;
  1798. }
  1799. }
  1800. return false;
  1801. }
  1802. /// <summary>
  1803. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, does nothing.
  1804. /// </summary>
  1805. public void EnsureFocus ()
  1806. {
  1807. if (focused == null && subviews?.Count > 0) {
  1808. if (FocusDirection == Direction.Forward) {
  1809. FocusFirst ();
  1810. } else {
  1811. FocusLast ();
  1812. }
  1813. }
  1814. }
  1815. /// <summary>
  1816. /// Focuses the first focusable subview if one exists.
  1817. /// </summary>
  1818. public void FocusFirst ()
  1819. {
  1820. if (!CanBeVisible (this)) {
  1821. return;
  1822. }
  1823. if (tabIndexes == null) {
  1824. SuperView?.SetFocus (this);
  1825. return;
  1826. }
  1827. foreach (var view in tabIndexes) {
  1828. if (view.CanFocus && view.tabStop && view.Visible && view.Enabled) {
  1829. SetFocus (view);
  1830. return;
  1831. }
  1832. }
  1833. }
  1834. /// <summary>
  1835. /// Focuses the last focusable subview if one exists.
  1836. /// </summary>
  1837. public void FocusLast ()
  1838. {
  1839. if (!CanBeVisible (this)) {
  1840. return;
  1841. }
  1842. if (tabIndexes == null) {
  1843. SuperView?.SetFocus (this);
  1844. return;
  1845. }
  1846. for (var i = tabIndexes.Count; i > 0;) {
  1847. i--;
  1848. var v = tabIndexes [i];
  1849. if (v.CanFocus && v.tabStop && v.Visible && v.Enabled) {
  1850. SetFocus (v);
  1851. return;
  1852. }
  1853. }
  1854. }
  1855. /// <summary>
  1856. /// Focuses the previous view.
  1857. /// </summary>
  1858. /// <returns><see langword="true"/> if previous was focused, <see langword="false"/> otherwise.</returns>
  1859. public bool FocusPrev ()
  1860. {
  1861. if (!CanBeVisible (this)) {
  1862. return false;
  1863. }
  1864. FocusDirection = Direction.Backward;
  1865. if (tabIndexes == null || tabIndexes.Count == 0)
  1866. return false;
  1867. if (focused == null) {
  1868. FocusLast ();
  1869. return focused != null;
  1870. }
  1871. var focusedIdx = -1;
  1872. for (var i = tabIndexes.Count; i > 0;) {
  1873. i--;
  1874. var w = tabIndexes [i];
  1875. if (w.HasFocus) {
  1876. if (w.FocusPrev ())
  1877. return true;
  1878. focusedIdx = i;
  1879. continue;
  1880. }
  1881. if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
  1882. focused.SetHasFocus (false, w);
  1883. if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  1884. w.FocusLast ();
  1885. SetFocus (w);
  1886. return true;
  1887. }
  1888. }
  1889. if (focused != null) {
  1890. focused.SetHasFocus (false, this);
  1891. focused = null;
  1892. }
  1893. return false;
  1894. }
  1895. /// <summary>
  1896. /// Focuses the next view.
  1897. /// </summary>
  1898. /// <returns><see langword="true"/> if next was focused, <see langword="false"/> otherwise.</returns>
  1899. public bool FocusNext ()
  1900. {
  1901. if (!CanBeVisible (this)) {
  1902. return false;
  1903. }
  1904. FocusDirection = Direction.Forward;
  1905. if (tabIndexes == null || tabIndexes.Count == 0)
  1906. return false;
  1907. if (focused == null) {
  1908. FocusFirst ();
  1909. return focused != null;
  1910. }
  1911. var n = tabIndexes.Count;
  1912. var focusedIdx = -1;
  1913. for (var i = 0; i < n; i++) {
  1914. var w = tabIndexes [i];
  1915. if (w.HasFocus) {
  1916. if (w.FocusNext ())
  1917. return true;
  1918. focusedIdx = i;
  1919. continue;
  1920. }
  1921. if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
  1922. focused.SetHasFocus (false, w);
  1923. if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
  1924. w.FocusFirst ();
  1925. SetFocus (w);
  1926. return true;
  1927. }
  1928. }
  1929. if (focused != null) {
  1930. focused.SetHasFocus (false, this);
  1931. focused = null;
  1932. }
  1933. return false;
  1934. }
  1935. View GetMostFocused (View view)
  1936. {
  1937. if (view == null) {
  1938. return null;
  1939. }
  1940. return view.focused != null ? GetMostFocused (view.focused) : view;
  1941. }
  1942. /// <summary>
  1943. /// Sets the View's <see cref="Frame"/> to the frame-relative coordinates if its container. The
  1944. /// container size and location are specified by <paramref name="superviewFrame"/> and are relative to the
  1945. /// View's superview.
  1946. /// </summary>
  1947. /// <param name="superviewFrame">The supserview-relative rectangle describing View's container (nominally the
  1948. /// same as <c>this.SuperView.Frame</c>).</param>
  1949. internal void SetRelativeLayout (Rect superviewFrame)
  1950. {
  1951. int newX, newW, newY, newH;
  1952. var autosize = Size.Empty;
  1953. if (AutoSize) {
  1954. // Note this is global to this function and used as such within the local functions defined
  1955. // below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
  1956. autosize = GetAutoSize ();
  1957. }
  1958. // Returns the new dimension (width or height) and location (x or y) for the View given
  1959. // the superview's Frame.X or Frame.Y
  1960. // the superview's width or height
  1961. // the current Pos (View.X or View.Y)
  1962. // the current Dim (View.Width or View.Height)
  1963. (int newLocation, int newDimension) GetNewLocationAndDimension (int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
  1964. {
  1965. int newDimension, newLocation;
  1966. switch (pos) {
  1967. case Pos.PosCenter:
  1968. if (dim == null) {
  1969. newDimension = AutoSize ? autosizeDimension : superviewDimension;
  1970. } else {
  1971. newDimension = dim.Anchor (superviewDimension);
  1972. newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
  1973. }
  1974. newLocation = pos.Anchor (superviewDimension - newDimension);
  1975. break;
  1976. case Pos.PosCombine combine:
  1977. int left, right;
  1978. (left, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.left, dim, autosizeDimension);
  1979. (right, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.right, dim, autosizeDimension);
  1980. if (combine.add) {
  1981. newLocation = left + right;
  1982. } else {
  1983. newLocation = left - right;
  1984. }
  1985. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  1986. break;
  1987. case Pos.PosAbsolute:
  1988. case Pos.PosAnchorEnd:
  1989. case Pos.PosFactor:
  1990. case Pos.PosFunc:
  1991. case Pos.PosView:
  1992. default:
  1993. newLocation = pos?.Anchor (superviewDimension) ?? 0;
  1994. newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
  1995. break;
  1996. }
  1997. return (newLocation, newDimension);
  1998. }
  1999. // Recursively calculates the new dimension (width or height) of the given Dim given:
  2000. // the current location (x or y)
  2001. // the current dimension (width or height)
  2002. int CalculateNewDimension (Dim d, int location, int dimension, int autosize)
  2003. {
  2004. int newDimension;
  2005. switch (d) {
  2006. case null:
  2007. newDimension = AutoSize ? autosize : dimension;
  2008. break;
  2009. case Dim.DimCombine combine:
  2010. int leftNewDim = CalculateNewDimension (combine.left, location, dimension, autosize);
  2011. int rightNewDim = CalculateNewDimension (combine.right, location, dimension, autosize);
  2012. if (combine.add) {
  2013. newDimension = leftNewDim + rightNewDim;
  2014. } else {
  2015. newDimension = leftNewDim - rightNewDim;
  2016. }
  2017. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2018. break;
  2019. case Dim.DimFactor factor when !factor.IsFromRemaining ():
  2020. newDimension = d.Anchor (dimension);
  2021. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2022. break;
  2023. case Dim.DimFill:
  2024. default:
  2025. newDimension = Math.Max (d.Anchor (dimension - location), 0);
  2026. newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
  2027. break;
  2028. }
  2029. return newDimension;
  2030. }
  2031. // horizontal
  2032. (newX, newW) = GetNewLocationAndDimension (superviewFrame.X, superviewFrame.Width, x, width, autosize.Width);
  2033. // vertical
  2034. (newY, newH) = GetNewLocationAndDimension (superviewFrame.Y, superviewFrame.Height, y, height, autosize.Height);
  2035. var r = new Rect (newX, newY, newW, newH);
  2036. if (Frame != r) {
  2037. Frame = r;
  2038. if (!SetMinWidthHeight ()) {
  2039. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2040. }
  2041. }
  2042. }
  2043. /// <summary>
  2044. /// Event arguments for the <see cref="LayoutComplete"/> event.
  2045. /// </summary>
  2046. public class LayoutEventArgs : EventArgs {
  2047. /// <summary>
  2048. /// The view-relative bounds of the <see cref="View"/> before it was laid out.
  2049. /// </summary>
  2050. public Rect OldBounds { get; set; }
  2051. }
  2052. /// <summary>
  2053. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2054. /// </summary>
  2055. /// <remarks>
  2056. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2057. /// </remarks>
  2058. public event Action<LayoutEventArgs> LayoutStarted;
  2059. /// <summary>
  2060. /// Raises the <see cref="LayoutStarted"/> event. Called from <see cref="LayoutSubviews"/> before any subviews have been laid out.
  2061. /// </summary>
  2062. internal virtual void OnLayoutStarted (LayoutEventArgs args)
  2063. {
  2064. LayoutStarted?.Invoke (args);
  2065. }
  2066. /// <summary>
  2067. /// Fired after the View's <see cref="LayoutSubviews"/> method has completed.
  2068. /// </summary>
  2069. /// <remarks>
  2070. /// Subscribe to this event to perform tasks when the <see cref="View"/> has been resized or the layout has otherwise changed.
  2071. /// </remarks>
  2072. public event Action<LayoutEventArgs> LayoutComplete;
  2073. /// <summary>
  2074. /// Event called only once when the <see cref="View"/> is being initialized for the first time.
  2075. /// Allows configurations and assignments to be performed before the <see cref="View"/> being shown.
  2076. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  2077. /// </summary>
  2078. public event EventHandler Initialized;
  2079. /// <summary>
  2080. /// Raises the <see cref="LayoutComplete"/> event. Called from <see cref="LayoutSubviews"/> before all sub-views have been laid out.
  2081. /// </summary>
  2082. internal virtual void OnLayoutComplete (LayoutEventArgs args)
  2083. {
  2084. LayoutComplete?.Invoke (args);
  2085. }
  2086. internal void CollectPos (Pos pos, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2087. {
  2088. switch (pos) {
  2089. case Pos.PosView pv:
  2090. if (pv.Target != this) {
  2091. nEdges.Add ((pv.Target, from));
  2092. }
  2093. foreach (var v in from.InternalSubviews) {
  2094. CollectAll (v, ref nNodes, ref nEdges);
  2095. }
  2096. return;
  2097. case Pos.PosCombine pc:
  2098. foreach (var v in from.InternalSubviews) {
  2099. CollectPos (pc.left, from, ref nNodes, ref nEdges);
  2100. CollectPos (pc.right, from, ref nNodes, ref nEdges);
  2101. }
  2102. break;
  2103. }
  2104. }
  2105. internal void CollectDim (Dim dim, View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2106. {
  2107. switch (dim) {
  2108. case Dim.DimView dv:
  2109. if (dv.Target != this) {
  2110. nEdges.Add ((dv.Target, from));
  2111. }
  2112. foreach (var v in from.InternalSubviews) {
  2113. CollectAll (v, ref nNodes, ref nEdges);
  2114. }
  2115. return;
  2116. case Dim.DimCombine dc:
  2117. foreach (var v in from.InternalSubviews) {
  2118. CollectDim (dc.left, from, ref nNodes, ref nEdges);
  2119. CollectDim (dc.right, from, ref nNodes, ref nEdges);
  2120. }
  2121. break;
  2122. }
  2123. }
  2124. internal void CollectAll (View from, ref HashSet<View> nNodes, ref HashSet<(View, View)> nEdges)
  2125. {
  2126. foreach (var v in from.InternalSubviews) {
  2127. nNodes.Add (v);
  2128. if (v.layoutStyle != LayoutStyle.Computed) {
  2129. continue;
  2130. }
  2131. CollectPos (v.X, v, ref nNodes, ref nEdges);
  2132. CollectPos (v.Y, v, ref nNodes, ref nEdges);
  2133. CollectDim (v.Width, v, ref nNodes, ref nEdges);
  2134. CollectDim (v.Height, v, ref nNodes, ref nEdges);
  2135. }
  2136. }
  2137. // https://en.wikipedia.org/wiki/Topological_sorting
  2138. internal static List<View> TopologicalSort (View superView, IEnumerable<View> nodes, ICollection<(View From, View To)> edges)
  2139. {
  2140. var result = new List<View> ();
  2141. // Set of all nodes with no incoming edges
  2142. var noEdgeNodes = new HashSet<View> (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
  2143. while (noEdgeNodes.Any ()) {
  2144. // remove a node n from S
  2145. var n = noEdgeNodes.First ();
  2146. noEdgeNodes.Remove (n);
  2147. // add n to tail of L
  2148. if (n != superView)
  2149. result.Add (n);
  2150. // for each node m with an edge e from n to m do
  2151. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  2152. var m = e.To;
  2153. // remove edge e from the graph
  2154. edges.Remove (e);
  2155. // if m has no other incoming edges then
  2156. if (edges.All (me => !me.To.Equals (m)) && m != superView) {
  2157. // insert m into S
  2158. noEdgeNodes.Add (m);
  2159. }
  2160. }
  2161. }
  2162. if (edges.Any ()) {
  2163. (var from, var to) = edges.First ();
  2164. if (from != superView?.GetTopSuperView (to, from)) {
  2165. if (!ReferenceEquals (from, to)) {
  2166. throw new InvalidOperationException ($"TopologicalSort (for Pos/Dim) cannot find {from} linked with {to}. Did you forget to add it to {superView}?");
  2167. } else {
  2168. throw new InvalidOperationException ("TopologicalSort encountered a recursive cycle in the relative Pos/Dim in the views of " + superView);
  2169. }
  2170. }
  2171. }
  2172. // return L (a topologically sorted order)
  2173. return result;
  2174. } // TopologicalSort
  2175. /// <summary>
  2176. /// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
  2177. /// response to the container view or terminal resizing.
  2178. /// </summary>
  2179. /// <remarks>
  2180. /// Calls <see cref="OnLayoutComplete"/> (which raises the <see cref="LayoutComplete"/> event) before it returns.
  2181. /// </remarks>
  2182. public virtual void LayoutSubviews ()
  2183. {
  2184. if (!LayoutNeeded) {
  2185. return;
  2186. }
  2187. var oldBounds = Bounds;
  2188. OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
  2189. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2190. // Sort out the dependencies of the X, Y, Width, Height properties
  2191. var nodes = new HashSet<View> ();
  2192. var edges = new HashSet<(View, View)> ();
  2193. CollectAll (this, ref nodes, ref edges);
  2194. var ordered = View.TopologicalSort (SuperView, nodes, edges);
  2195. foreach (var v in ordered) {
  2196. LayoutSubview (v, Frame);
  2197. }
  2198. // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
  2199. // Use LayoutSubview with the Frame of the 'from'
  2200. if (SuperView != null && GetTopSuperView () != null && LayoutNeeded
  2201. && ordered.Count == 0 && edges.Count > 0 && LayoutStyle == LayoutStyle.Computed) {
  2202. (var from, var to) = edges.First ();
  2203. LayoutSubview (to, from.Frame);
  2204. }
  2205. LayoutNeeded = false;
  2206. OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
  2207. }
  2208. private void LayoutSubview (View v, Rect hostFrame)
  2209. {
  2210. if (v.LayoutStyle == LayoutStyle.Computed) {
  2211. v.SetRelativeLayout (hostFrame);
  2212. }
  2213. v.LayoutSubviews ();
  2214. v.LayoutNeeded = false;
  2215. }
  2216. ustring text;
  2217. /// <summary>
  2218. /// The text displayed by the <see cref="View"/>.
  2219. /// </summary>
  2220. /// <remarks>
  2221. /// <para>
  2222. /// If provided, the text will be drawn before any subviews are drawn.
  2223. /// </para>
  2224. /// <para>
  2225. /// The text will be drawn starting at the view origin (0, 0) and will be formatted according
  2226. /// to the <see cref="TextAlignment"/> property. If the view's height is greater than 1, the
  2227. /// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
  2228. /// is 1, the text will be clipped.
  2229. /// </para>
  2230. /// <para>
  2231. /// Set the <see cref="HotKeySpecifier"/> to enable hotkey support. To disable hotkey support set <see cref="HotKeySpecifier"/> to
  2232. /// <c>(Rune)0xffff</c>.
  2233. /// </para>
  2234. /// </remarks>
  2235. public virtual ustring Text {
  2236. get => text;
  2237. set {
  2238. text = value;
  2239. SetHotKey ();
  2240. UpdateTextFormatterText ();
  2241. ProcessResizeView ();
  2242. }
  2243. }
  2244. /// <summary>
  2245. /// Gets or sets a flag that determines whether the View will be automatically resized to fit the <see cref="Text"/>.
  2246. /// 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"/>
  2247. /// and <see cref="Height"/> will always be used if the text size is lower. If the text size is higher the bounds will
  2248. /// be resized to fit it.
  2249. /// In addition, if <see cref="ForceValidatePosDim"/> is <see langword="true"/> the new values of <see cref="Width"/> and
  2250. /// <see cref="Height"/> must be of the same types of the existing one to avoid breaking the <see cref="Dim"/> settings.
  2251. /// </summary>
  2252. public virtual bool AutoSize {
  2253. get => autoSize;
  2254. set {
  2255. var v = ResizeView (value);
  2256. TextFormatter.AutoSize = v;
  2257. if (autoSize != v) {
  2258. autoSize = v;
  2259. TextFormatter.NeedsFormat = true;
  2260. UpdateTextFormatterText ();
  2261. ProcessResizeView ();
  2262. }
  2263. }
  2264. }
  2265. /// <summary>
  2266. /// Gets or sets a flag that determines whether <see cref="Terminal.Gui.TextFormatter.Text"/> will have trailing spaces preserved
  2267. /// or not when <see cref="Terminal.Gui.TextFormatter.WordWrap"/> is enabled. If <see langword="true"/>
  2268. /// any trailing spaces will be trimmed when either the <see cref="Text"/> property is changed or
  2269. /// when <see cref="Terminal.Gui.TextFormatter.WordWrap"/> is set to <see langword="true"/>.
  2270. /// The default is <see langword="false"/>.
  2271. /// </summary>
  2272. public virtual bool PreserveTrailingSpaces {
  2273. get => TextFormatter.PreserveTrailingSpaces;
  2274. set {
  2275. if (TextFormatter.PreserveTrailingSpaces != value) {
  2276. TextFormatter.PreserveTrailingSpaces = value;
  2277. TextFormatter.NeedsFormat = true;
  2278. }
  2279. }
  2280. }
  2281. /// <summary>
  2282. /// Gets or sets how the View's <see cref="Text"/> is aligned horizontally when drawn. Changing this property will redisplay the <see cref="View"/>.
  2283. /// </summary>
  2284. /// <value>The text alignment.</value>
  2285. public virtual TextAlignment TextAlignment {
  2286. get => TextFormatter.Alignment;
  2287. set {
  2288. TextFormatter.Alignment = value;
  2289. UpdateTextFormatterText ();
  2290. ProcessResizeView ();
  2291. }
  2292. }
  2293. /// <summary>
  2294. /// Gets or sets how the View's <see cref="Text"/> is aligned vertically when drawn. Changing this property will redisplay the <see cref="View"/>.
  2295. /// </summary>
  2296. /// <value>The text alignment.</value>
  2297. public virtual VerticalTextAlignment VerticalTextAlignment {
  2298. get => TextFormatter.VerticalAlignment;
  2299. set {
  2300. TextFormatter.VerticalAlignment = value;
  2301. SetNeedsDisplay ();
  2302. }
  2303. }
  2304. /// <summary>
  2305. /// Gets or sets the direction of the View's <see cref="Text"/>. Changing this property will redisplay the <see cref="View"/>.
  2306. /// </summary>
  2307. /// <value>The text alignment.</value>
  2308. public virtual TextDirection TextDirection {
  2309. get => TextFormatter.Direction;
  2310. set {
  2311. if (TextFormatter.Direction != value) {
  2312. var isValidOldAutSize = autoSize && IsValidAutoSize (out var _);
  2313. var directionChanged = TextFormatter.IsHorizontalDirection (TextFormatter.Direction)
  2314. != TextFormatter.IsHorizontalDirection (value);
  2315. TextFormatter.Direction = value;
  2316. UpdateTextFormatterText ();
  2317. if ((!ForceValidatePosDim && directionChanged && AutoSize)
  2318. || (ForceValidatePosDim && directionChanged && AutoSize && isValidOldAutSize)) {
  2319. ProcessResizeView ();
  2320. } else if (directionChanged && IsAdded) {
  2321. SetWidthHeight (Bounds.Size);
  2322. SetMinWidthHeight ();
  2323. } else {
  2324. SetMinWidthHeight ();
  2325. }
  2326. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2327. SetNeedsDisplay ();
  2328. }
  2329. }
  2330. }
  2331. /// <summary>
  2332. /// Get or sets if the <see cref="View"/> was already initialized.
  2333. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are being initialized.
  2334. /// </summary>
  2335. public virtual bool IsInitialized { get; set; }
  2336. /// <summary>
  2337. /// Gets information if the view was already added to the <see cref="SuperView"/>.
  2338. /// </summary>
  2339. public bool IsAdded { get; private set; }
  2340. bool oldEnabled;
  2341. /// <inheritdoc/>
  2342. public override bool Enabled {
  2343. get => base.Enabled;
  2344. set {
  2345. if (base.Enabled != value) {
  2346. if (value) {
  2347. if (SuperView == null || SuperView?.Enabled == true) {
  2348. base.Enabled = value;
  2349. }
  2350. } else {
  2351. base.Enabled = value;
  2352. }
  2353. if (!value && HasFocus) {
  2354. SetHasFocus (false, this);
  2355. }
  2356. OnEnabledChanged ();
  2357. SetNeedsDisplay ();
  2358. if (subviews != null) {
  2359. foreach (var view in subviews) {
  2360. if (!value) {
  2361. view.oldEnabled = view.Enabled;
  2362. view.Enabled = false;
  2363. } else {
  2364. view.Enabled = view.oldEnabled;
  2365. view.addingView = false;
  2366. }
  2367. }
  2368. }
  2369. }
  2370. }
  2371. }
  2372. /// <summary>
  2373. /// Gets or sets whether a view is cleared if the <see cref="Visible"/> property is <see langword="false"/>.
  2374. /// </summary>
  2375. public bool ClearOnVisibleFalse { get; set; } = true;
  2376. /// <inheritdoc/>>
  2377. public override bool Visible {
  2378. get => base.Visible;
  2379. set {
  2380. if (base.Visible != value) {
  2381. base.Visible = value;
  2382. if (!value) {
  2383. if (HasFocus) {
  2384. SetHasFocus (false, this);
  2385. }
  2386. if (ClearOnVisibleFalse) {
  2387. Clear ();
  2388. }
  2389. }
  2390. OnVisibleChanged ();
  2391. SetNeedsDisplay ();
  2392. }
  2393. }
  2394. }
  2395. Border border;
  2396. /// <inheritdoc/>
  2397. public virtual Border Border {
  2398. get => border;
  2399. set {
  2400. if (border != value) {
  2401. border = value;
  2402. SetNeedsDisplay ();
  2403. }
  2404. }
  2405. }
  2406. /// <summary>
  2407. /// Get or sets whether the view will use <see cref="Terminal.Gui.Border"/> (if <see cref="Border"/> is set) to draw
  2408. /// a border. If <see langword="false"/> (the default),
  2409. /// <see cref="View.Redraw(Rect)"/> will call <see cref="Border.DrawContent(View, bool)"/>
  2410. /// to draw the view's border. If <see langword="true"/> no border is drawn (and the view is expected to draw the border
  2411. /// itself).
  2412. /// </summary>
  2413. public virtual bool IgnoreBorderPropertyOnRedraw { get; set; }
  2414. /// <summary>
  2415. /// Pretty prints the View
  2416. /// </summary>
  2417. /// <returns></returns>
  2418. public override string ToString ()
  2419. {
  2420. return $"{GetType ().Name}({Id})({Frame})";
  2421. }
  2422. void SetHotKey ()
  2423. {
  2424. TextFormatter.FindHotKey (text, HotKeySpecifier, true, out _, out var hk);
  2425. if (hotKey != hk) {
  2426. HotKey = hk;
  2427. }
  2428. }
  2429. bool ResizeView (bool autoSize)
  2430. {
  2431. if (!autoSize) {
  2432. return false;
  2433. }
  2434. var aSize = true;
  2435. var nBoundsSize = GetAutoSize ();
  2436. if (nBoundsSize != Bounds.Size) {
  2437. if (ForceValidatePosDim) {
  2438. aSize = SetWidthHeight (nBoundsSize);
  2439. } else {
  2440. Bounds = new Rect (Bounds.X, Bounds.Y, nBoundsSize.Width, nBoundsSize.Height);
  2441. }
  2442. }
  2443. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2444. return aSize;
  2445. }
  2446. bool SetWidthHeight (Size nBounds)
  2447. {
  2448. var aSize = false;
  2449. var canSizeW = SetWidth (nBounds.Width - GetHotKeySpecifierLength (), out var rW);
  2450. var canSizeH = SetHeight (nBounds.Height - GetHotKeySpecifierLength (false), out var rH);
  2451. if (canSizeW) {
  2452. aSize = true;
  2453. width = rW;
  2454. }
  2455. if (canSizeH) {
  2456. aSize = true;
  2457. height = rH;
  2458. }
  2459. if (aSize) {
  2460. Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
  2461. TextFormatter.Size = GetBoundsTextFormatterSize ();
  2462. }
  2463. return aSize;
  2464. }
  2465. /// <summary>
  2466. /// Gets the dimensions required to fit <see cref="Text"/> using the text <see cref="Direction"/> specified by the
  2467. /// <see cref="TextFormatter"/> property and accounting for any <see cref="HotKeySpecifier"/> characters.
  2468. /// .
  2469. /// </summary>
  2470. /// <returns>The <see cref="Size"/> required to fit the text.</returns>
  2471. public Size GetAutoSize ()
  2472. {
  2473. var rect = TextFormatter.CalcRect (Bounds.X, Bounds.Y, TextFormatter.Text, TextFormatter.Direction);
  2474. return new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2475. rect.Size.Height - GetHotKeySpecifierLength (false));
  2476. }
  2477. bool IsValidAutoSize (out Size autoSize)
  2478. {
  2479. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2480. autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
  2481. rect.Size.Height - GetHotKeySpecifierLength (false));
  2482. return !(ForceValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
  2483. || frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
  2484. || frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
  2485. }
  2486. bool IsValidAutoSizeWidth (Dim width)
  2487. {
  2488. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2489. var dimValue = width.Anchor (0);
  2490. return !(ForceValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
  2491. - GetHotKeySpecifierLength ());
  2492. }
  2493. bool IsValidAutoSizeHeight (Dim height)
  2494. {
  2495. var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
  2496. var dimValue = height.Anchor (0);
  2497. return !(ForceValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
  2498. - GetHotKeySpecifierLength (false));
  2499. }
  2500. /// <summary>
  2501. /// Gets the width or height of the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> characters in the <see cref="Text"/> property.
  2502. /// </summary>
  2503. /// <param name="isWidth">If <see langword="true"/> (the default) the width required for the hotkey specifier is returned. Otherwise the height is returned.</param>
  2504. /// <returns>The number of characters required for the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>. If the text direction specified
  2505. /// by <see cref="TextDirection"/> does not match the <paramref name="isWidth"/> parameter, <c>0</c> is returned.</returns>
  2506. public int GetHotKeySpecifierLength (bool isWidth = true)
  2507. {
  2508. if (isWidth) {
  2509. return TextFormatter.IsHorizontalDirection (TextDirection) &&
  2510. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2511. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2512. } else {
  2513. return TextFormatter.IsVerticalDirection (TextDirection) &&
  2514. TextFormatter.Text?.Contains (HotKeySpecifier) == true
  2515. ? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
  2516. }
  2517. }
  2518. /// <summary>
  2519. /// Gets the <see cref="TextFormatter.Size"/> minus the size required for the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/>.
  2520. /// </summary>
  2521. /// <returns>The bounds size minus the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> length.</returns>
  2522. public Size GetTextFormatterBoundsSize ()
  2523. {
  2524. return new Size (TextFormatter.Size.Width - GetHotKeySpecifierLength (),
  2525. TextFormatter.Size.Height - GetHotKeySpecifierLength (false));
  2526. }
  2527. /// <summary>
  2528. /// Gets the text formatter size from a <see cref="Bounds"/> size.
  2529. /// </summary>
  2530. /// <returns>The text formatter size more the <see cref="Terminal.Gui.TextFormatter.HotKeySpecifier"/> length.</returns>
  2531. public Size GetBoundsTextFormatterSize ()
  2532. {
  2533. if (ustring.IsNullOrEmpty (TextFormatter.Text))
  2534. return Bounds.Size;
  2535. return new Size (frame.Size.Width + GetHotKeySpecifierLength (),
  2536. frame.Size.Height + GetHotKeySpecifierLength (false));
  2537. }
  2538. /// <summary>
  2539. /// Specifies the event arguments for <see cref="MouseEvent"/>. This is a higher-level construct
  2540. /// than the wrapped <see cref="MouseEvent"/> class and is used for the events defined on <see cref="View"/>
  2541. /// and subclasses of View (e.g. <see cref="View.MouseEnter"/> and <see cref="View.MouseClick"/>).
  2542. /// </summary>
  2543. public class MouseEventArgs : EventArgs {
  2544. /// <summary>
  2545. /// Constructs.
  2546. /// </summary>
  2547. /// <param name="me"></param>
  2548. public MouseEventArgs (MouseEvent me) => MouseEvent = me;
  2549. /// <summary>
  2550. /// The <see cref="MouseEvent"/> for the event.
  2551. /// </summary>
  2552. public MouseEvent MouseEvent { get; set; }
  2553. /// <summary>
  2554. /// Indicates if the current mouse event has already been processed and the driver should stop notifying any other event subscriber.
  2555. /// Its important to set this value to true specially when updating any View's layout from inside the subscriber method.
  2556. /// </summary>
  2557. /// <remarks>This property forwards to the <see cref="MouseEvent.Handled"/> property and is provided as a convenience and for
  2558. /// backwards compatibility</remarks>
  2559. public bool Handled {
  2560. get => MouseEvent.Handled;
  2561. set => MouseEvent.Handled = value;
  2562. }
  2563. }
  2564. /// <inheritdoc/>
  2565. public override bool OnMouseEnter (MouseEvent mouseEvent)
  2566. {
  2567. if (!Enabled) {
  2568. return true;
  2569. }
  2570. if (!CanBeVisible (this)) {
  2571. return false;
  2572. }
  2573. var args = new MouseEventArgs (mouseEvent);
  2574. MouseEnter?.Invoke (args);
  2575. return args.Handled || base.OnMouseEnter (mouseEvent);
  2576. }
  2577. /// <inheritdoc/>
  2578. public override bool OnMouseLeave (MouseEvent mouseEvent)
  2579. {
  2580. if (!Enabled) {
  2581. return true;
  2582. }
  2583. if (!CanBeVisible (this)) {
  2584. return false;
  2585. }
  2586. var args = new MouseEventArgs (mouseEvent);
  2587. MouseLeave?.Invoke (args);
  2588. return args.Handled || base.OnMouseLeave (mouseEvent);
  2589. }
  2590. /// <summary>
  2591. /// Method invoked when a mouse event is generated
  2592. /// </summary>
  2593. /// <param name="mouseEvent"></param>
  2594. /// <returns><see langword="true"/>, if the event was handled, <see langword="false"/> otherwise.</returns>
  2595. public virtual bool OnMouseEvent (MouseEvent mouseEvent)
  2596. {
  2597. if (!Enabled) {
  2598. return true;
  2599. }
  2600. if (!CanBeVisible (this)) {
  2601. return false;
  2602. }
  2603. var args = new MouseEventArgs (mouseEvent);
  2604. if (OnMouseClick (args))
  2605. return true;
  2606. if (MouseEvent (mouseEvent))
  2607. return true;
  2608. if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
  2609. if (CanFocus && !HasFocus && SuperView != null) {
  2610. SuperView.SetFocus (this);
  2611. SetNeedsDisplay ();
  2612. }
  2613. return true;
  2614. }
  2615. return false;
  2616. }
  2617. /// <summary>
  2618. /// Invokes the MouseClick event.
  2619. /// </summary>
  2620. protected bool OnMouseClick (MouseEventArgs args)
  2621. {
  2622. if (!Enabled) {
  2623. return true;
  2624. }
  2625. MouseClick?.Invoke (args);
  2626. return args.Handled;
  2627. }
  2628. /// <inheritdoc/>
  2629. public override void OnCanFocusChanged () => CanFocusChanged?.Invoke ();
  2630. /// <inheritdoc/>
  2631. public override void OnEnabledChanged () => EnabledChanged?.Invoke ();
  2632. /// <inheritdoc/>
  2633. public override void OnVisibleChanged () => VisibleChanged?.Invoke ();
  2634. /// <inheritdoc/>
  2635. protected override void Dispose (bool disposing)
  2636. {
  2637. for (var i = InternalSubviews.Count - 1; i >= 0; i--) {
  2638. var subview = InternalSubviews [i];
  2639. Remove (subview);
  2640. subview.Dispose ();
  2641. }
  2642. base.Dispose (disposing);
  2643. }
  2644. /// <summary>
  2645. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are beginning initialized.
  2646. /// </summary>
  2647. public void BeginInit ()
  2648. {
  2649. if (!IsInitialized) {
  2650. oldCanFocus = CanFocus;
  2651. oldTabIndex = tabIndex;
  2652. }
  2653. if (subviews?.Count > 0) {
  2654. foreach (var view in subviews) {
  2655. if (!view.IsInitialized) {
  2656. view.BeginInit ();
  2657. }
  2658. }
  2659. }
  2660. }
  2661. /// <summary>
  2662. /// This derived from <see cref="ISupportInitializeNotification"/> to allow notify all the views that are ending initialized.
  2663. /// </summary>
  2664. public void EndInit ()
  2665. {
  2666. IsInitialized = true;
  2667. if (subviews?.Count > 0) {
  2668. foreach (var view in subviews) {
  2669. if (!view.IsInitialized) {
  2670. view.EndInit ();
  2671. }
  2672. }
  2673. }
  2674. Initialized?.Invoke (this, EventArgs.Empty);
  2675. }
  2676. bool CanBeVisible (View view)
  2677. {
  2678. if (!view.Visible) {
  2679. return false;
  2680. }
  2681. for (var c = view.SuperView; c != null; c = c.SuperView) {
  2682. if (!c.Visible) {
  2683. return false;
  2684. }
  2685. }
  2686. return true;
  2687. }
  2688. bool CanSetWidth (int desiredWidth, out int resultWidth)
  2689. {
  2690. var w = desiredWidth;
  2691. bool canSetWidth;
  2692. if (Width is Dim.DimCombine || Width is Dim.DimView || Width is Dim.DimFill) {
  2693. // It's a Dim.DimCombine and so can't be assigned. Let it have it's width anchored.
  2694. w = Width.Anchor (w);
  2695. canSetWidth = !ForceValidatePosDim;
  2696. } else if (Width is Dim.DimFactor factor) {
  2697. // Tries to get the SuperView width otherwise the view width.
  2698. var sw = SuperView != null ? SuperView.Frame.Width : w;
  2699. if (factor.IsFromRemaining ()) {
  2700. sw -= Frame.X;
  2701. }
  2702. w = Width.Anchor (sw);
  2703. canSetWidth = !ForceValidatePosDim;
  2704. } else {
  2705. canSetWidth = true;
  2706. }
  2707. resultWidth = w;
  2708. return canSetWidth;
  2709. }
  2710. bool CanSetHeight (int desiredHeight, out int resultHeight)
  2711. {
  2712. var h = desiredHeight;
  2713. bool canSetHeight;
  2714. switch (Height) {
  2715. case Dim.DimCombine _:
  2716. case Dim.DimView _:
  2717. case Dim.DimFill _:
  2718. // It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
  2719. h = Height.Anchor (h);
  2720. canSetHeight = !ForceValidatePosDim;
  2721. break;
  2722. case Dim.DimFactor factor:
  2723. // Tries to get the SuperView height otherwise the view height.
  2724. var sh = SuperView != null ? SuperView.Frame.Height : h;
  2725. if (factor.IsFromRemaining ()) {
  2726. sh -= Frame.Y;
  2727. }
  2728. h = Height.Anchor (sh);
  2729. canSetHeight = !ForceValidatePosDim;
  2730. break;
  2731. default:
  2732. canSetHeight = true;
  2733. break;
  2734. }
  2735. resultHeight = h;
  2736. return canSetHeight;
  2737. }
  2738. /// <summary>
  2739. /// Calculate the width based on the <see cref="Width"/> settings.
  2740. /// </summary>
  2741. /// <param name="desiredWidth">The desired width.</param>
  2742. /// <param name="resultWidth">The real result width.</param>
  2743. /// <returns><see langword="true"/> if the width can be directly assigned, <see langword="false"/> otherwise.</returns>
  2744. public bool SetWidth (int desiredWidth, out int resultWidth)
  2745. {
  2746. return CanSetWidth (desiredWidth, out resultWidth);
  2747. }
  2748. /// <summary>
  2749. /// Calculate the height based on the <see cref="Height"/> settings.
  2750. /// </summary>
  2751. /// <param name="desiredHeight">The desired height.</param>
  2752. /// <param name="resultHeight">The real result height.</param>
  2753. /// <returns><see langword="true"/> if the height can be directly assigned, <see langword="false"/> otherwise.</returns>
  2754. public bool SetHeight (int desiredHeight, out int resultHeight)
  2755. {
  2756. return CanSetHeight (desiredHeight, out resultHeight);
  2757. }
  2758. /// <summary>
  2759. /// Gets the current width based on the <see cref="Width"/> settings.
  2760. /// </summary>
  2761. /// <param name="currentWidth">The real current width.</param>
  2762. /// <returns><see langword="true"/> if the width can be directly assigned, <see langword="false"/> otherwise.</returns>
  2763. public bool GetCurrentWidth (out int currentWidth)
  2764. {
  2765. SetRelativeLayout (SuperView?.frame ?? frame);
  2766. currentWidth = frame.Width;
  2767. return CanSetWidth (0, out _);
  2768. }
  2769. /// <summary>
  2770. /// Calculate the height based on the <see cref="Height"/> settings.
  2771. /// </summary>
  2772. /// <param name="currentHeight">The real current height.</param>
  2773. /// <returns><see langword="true"/> if the height can be directly assigned, <see langword="false"/> otherwise.</returns>
  2774. public bool GetCurrentHeight (out int currentHeight)
  2775. {
  2776. SetRelativeLayout (SuperView?.frame ?? frame);
  2777. currentHeight = frame.Height;
  2778. return CanSetHeight (0, out _);
  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.Normal"/> 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 GetNormalColor ()
  2787. {
  2788. return Enabled ? ColorScheme.Normal : ColorScheme.Disabled;
  2789. }
  2790. /// <summary>
  2791. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  2792. /// </summary>
  2793. /// <returns><see cref="Terminal.Gui.ColorScheme.Focus"/> if <see cref="Enabled"/> is <see langword="true"/>
  2794. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  2795. /// If it's overridden can return other values.</returns>
  2796. public virtual Attribute GetFocusColor ()
  2797. {
  2798. return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  2799. }
  2800. /// <summary>
  2801. /// Determines the current <see cref="ColorScheme"/> based on the <see cref="Enabled"/> value.
  2802. /// </summary>
  2803. /// <returns><see cref="Terminal.Gui.ColorScheme.HotNormal"/> if <see cref="Enabled"/> is <see langword="true"/>
  2804. /// or <see cref="Terminal.Gui.ColorScheme.Disabled"/> if <see cref="Enabled"/> is <see langword="false"/>.
  2805. /// If it's overridden can return other values.</returns>
  2806. public virtual Attribute GetHotNormalColor ()
  2807. {
  2808. return Enabled ? ColorScheme.HotNormal : ColorScheme.Disabled;
  2809. }
  2810. /// <summary>
  2811. /// Get the top superview of a given <see cref="View"/>.
  2812. /// </summary>
  2813. /// <returns>The superview view.</returns>
  2814. public View GetTopSuperView (View view = null, View superview = null)
  2815. {
  2816. View top = superview ?? Application.Top;
  2817. for (var v = view?.SuperView ?? (this?.SuperView); v != null; v = v.SuperView) {
  2818. top = v;
  2819. if (top == superview) {
  2820. break;
  2821. }
  2822. }
  2823. return top;
  2824. }
  2825. }
  2826. }