View.cs 101 KB

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