View.cs 102 KB

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