View.cs 102 KB

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