View.cs 85 KB

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