View.cs 83 KB

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