View.cs 83 KB

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