View.cs 104 KB

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