View.cs 73 KB

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