Color.cs 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. global using Attribute = Terminal.Gui.Attribute;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Immutable;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Linq;
  7. using System.Runtime.CompilerServices;
  8. using System.Text.Json.Serialization;
  9. using System.Text.RegularExpressions;
  10. namespace Terminal.Gui {
  11. /// <summary>
  12. /// Defines the 16 legacy color names and values that can be used to set the foreground and background colors in Terminal.Gui apps. Used with <see cref="Color"/>.
  13. /// </summary>
  14. /// <remarks>
  15. ///
  16. /// </remarks>
  17. public enum ColorNames {
  18. /// <summary>
  19. /// The black color.
  20. /// </summary>
  21. Black,
  22. /// <summary>
  23. /// The blue color.
  24. /// </summary>
  25. Blue,
  26. /// <summary>
  27. /// The green color.
  28. /// </summary>
  29. Green,
  30. /// <summary>
  31. /// The cyan color.
  32. /// </summary>
  33. Cyan,
  34. /// <summary>
  35. /// The red color.
  36. /// </summary>
  37. Red,
  38. /// <summary>
  39. /// The magenta color.
  40. /// </summary>
  41. Magenta,
  42. /// <summary>
  43. /// The brown color.
  44. /// </summary>
  45. Brown,
  46. /// <summary>
  47. /// The gray color.
  48. /// </summary>
  49. Gray,
  50. /// <summary>
  51. /// The dark gray color.
  52. /// </summary>
  53. DarkGray,
  54. /// <summary>
  55. /// The bright bBlue color.
  56. /// </summary>
  57. BrightBlue,
  58. /// <summary>
  59. /// The bright green color.
  60. /// </summary>
  61. BrightGreen,
  62. /// <summary>
  63. /// The bright cyan color.
  64. /// </summary>
  65. BrightCyan,
  66. /// <summary>
  67. /// The bright red color.
  68. /// </summary>
  69. BrightRed,
  70. /// <summary>
  71. /// The bright magenta color.
  72. /// </summary>
  73. BrightMagenta,
  74. /// <summary>
  75. /// The bright yellow color.
  76. /// </summary>
  77. BrightYellow,
  78. /// <summary>
  79. /// The White color.
  80. /// </summary>
  81. White
  82. }
  83. /// <summary>
  84. /// Represents a color in the console. This is used with <see cref="Attribute"/>.
  85. /// </summary>
  86. [JsonConverter (typeof (ColorJsonConverter))]
  87. public class Color : IEquatable<Color> {
  88. /// <summary>
  89. /// Initializes a new instance of the <see cref="Color"/> class.
  90. /// </summary>
  91. /// <param name="red"></param>
  92. /// <param name="green"></param>
  93. /// <param name="blue"></param>
  94. public Color (int red, int green, int blue)
  95. {
  96. A = 0xFF;
  97. R = red;
  98. G = green;
  99. B = blue;
  100. }
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="Color"/> class.
  103. /// </summary>
  104. /// <param name="alpha"></param>
  105. /// <param name="red"></param>
  106. /// <param name="green"></param>
  107. /// <param name="blue"></param>
  108. public Color (int alpha, int red, int green, int blue)
  109. {
  110. A = alpha;
  111. R = red;
  112. G = green;
  113. B = blue;
  114. }
  115. /// <summary>
  116. /// Initializes a new instance of the <see cref="Color"/> class with an encoded 24-bit color value.
  117. /// </summary>
  118. /// <param name="argb">The encoded 24-bit color value.</param>
  119. public Color (int argb)
  120. {
  121. Value = argb;
  122. }
  123. /// <summary>
  124. /// Initializes a new instance of the <see cref="Color"/> color from a legacy 16-color value.
  125. /// </summary>
  126. /// <param name="colorName">The 16-color value.</param>
  127. public Color (ColorNames colorName)
  128. {
  129. var c = Color.FromColorName (colorName);
  130. A = c.A;
  131. R = c.R;
  132. G = c.G;
  133. B = c.B;
  134. }
  135. /// <summary>
  136. /// Initializes a new instance of the <see cref="Color"/>.
  137. /// </summary>
  138. public Color ()
  139. {
  140. A = 0xFF;
  141. R = 0;
  142. G = 0;
  143. B = 0;
  144. }
  145. /// <summary>
  146. /// Red color component.
  147. /// </summary>
  148. public int R { get; set; }
  149. /// <summary>
  150. /// Green color component.
  151. /// </summary>
  152. public int G { get; set; }
  153. /// <summary>
  154. /// Blue color component.
  155. /// </summary>
  156. public int B { get; set; }
  157. /// <summary>
  158. /// Alpha color component.
  159. /// </summary>
  160. /// <remarks>
  161. /// Not currently supported; here for completeness.
  162. /// </remarks>
  163. public int A { get; set; }
  164. /// <summary>
  165. /// Gets or sets the color value encoded using the following code:
  166. /// <code>
  167. /// (&lt;see cref="A"/&gt; &lt;&lt; 24) | (&lt;see cref="R"/&gt; &lt;&lt; 16) | (&lt;see cref="G"/&gt; &lt;&lt; 8) | &lt;see cref="B"/&gt;
  168. /// </code>
  169. /// </summary>
  170. public int Value {
  171. get => (A << 24) | (R << 16) | (G << 8) | B;
  172. set {
  173. A = (byte)((value >> 24) & 0xFF);
  174. R = (byte)((value >> 16) & 0xFF);
  175. G = (byte)((value >> 8) & 0xFF);
  176. B = (byte)(value & 0xFF);
  177. }
  178. }
  179. // TODO: Make this map configurable via ConfigurationManager
  180. // TODO: This does not need to be a Dictionary, but can be an 16 element array.
  181. /// <summary>
  182. /// Maps legacy 16-color values to the corresponding 24-bit RGB value.
  183. /// </summary>
  184. internal static readonly ImmutableDictionary<Color, ColorNames> _colorNames = new Dictionary<Color, ColorNames> () {
  185. // using "Windows 10 Console/PowerShell 6" here: https://i.stack.imgur.com/9UVnC.png
  186. { new Color (12, 12, 12),ColorNames.Black },
  187. { new Color (0, 55, 218),ColorNames.Blue },
  188. { new Color (19, 161, 14),ColorNames.Green},
  189. { new Color (58, 150, 221),ColorNames.Cyan},
  190. { new Color (197, 15, 31),ColorNames.Red},
  191. { new Color (136, 23, 152),ColorNames.Magenta},
  192. { new Color (128, 64, 32),ColorNames.Brown},
  193. { new Color (204, 204, 204),ColorNames.Gray},
  194. { new Color (118, 118, 118),ColorNames.DarkGray},
  195. { new Color (59, 120, 255),ColorNames.BrightBlue},
  196. { new Color (22, 198, 12),ColorNames.BrightGreen},
  197. { new Color (97, 214, 214),ColorNames.BrightCyan},
  198. { new Color (231, 72, 86),ColorNames.BrightRed},
  199. { new Color (180, 0, 158),ColorNames.BrightMagenta },
  200. { new Color (249, 241, 165),ColorNames.BrightYellow},
  201. { new Color (242, 242, 242),ColorNames.White},
  202. }.ToImmutableDictionary ();
  203. /// <summary>
  204. /// Converts a legacy <see cref="ColorNames"/> to a 24-bit <see cref="Color"/>.
  205. /// </summary>
  206. /// <param name="consoleColor">The <see cref="Color"/> to convert.</param>
  207. /// <returns></returns>
  208. private static Color FromColorName (ColorNames consoleColor) => _colorNames.FirstOrDefault (x => x.Value == consoleColor).Key;
  209. // Iterates through the entries in the _colorNames dictionary, calculates the
  210. // Euclidean distance between the input color and each dictionary color in RGB space,
  211. // and keeps track of the closest entry found so far. The function returns a KeyValuePair
  212. // representing the closest color entry and its associated color name.
  213. internal static ColorNames FindClosestColor (Color inputColor)
  214. {
  215. ColorNames closestColor = ColorNames.Black; // Default to Black
  216. double closestDistance = double.MaxValue;
  217. foreach (var colorEntry in _colorNames) {
  218. var distance = CalculateColorDistance (inputColor, colorEntry.Key);
  219. if (distance < closestDistance) {
  220. closestDistance = distance;
  221. closestColor = colorEntry.Value;
  222. }
  223. }
  224. return closestColor;
  225. }
  226. private static double CalculateColorDistance (Color color1, Color color2)
  227. {
  228. // Calculate the Euclidean distance between two colors
  229. var deltaR = (double)color1.R - (double)color2.R;
  230. var deltaG = (double)color1.G - (double)color2.G;
  231. var deltaB = (double)color1.B - (double)color2.B;
  232. return Math.Sqrt (deltaR * deltaR + deltaG * deltaG + deltaB * deltaB);
  233. }
  234. /// <summary>
  235. /// Gets or sets the <see cref="Color"/> using a legacy 16-color <see cref="ColorNames"/> value.
  236. /// </summary>
  237. /// <remarks>
  238. /// Get returns the closest 24-bit color value. Set sets the RGB value using a hard-coded map.
  239. /// </remarks>
  240. public ColorNames ColorName {
  241. get => FindClosestColor (this.Value);
  242. set {
  243. var c = FromColorName (value);
  244. A = c.A;
  245. R = c.R;
  246. G = c.G;
  247. B = c.B;
  248. }
  249. }
  250. #region Legacy Color Names
  251. /// <summary>
  252. ///
  253. /// The black color.
  254. /// </summary>
  255. public const ColorNames Black = ColorNames.Black;
  256. /// <summary>
  257. /// The blue color.
  258. /// </summary>
  259. public const ColorNames Blue = ColorNames.Blue;
  260. /// <summary>
  261. /// The green color.
  262. /// </summary>
  263. public const ColorNames Green = ColorNames.Green;
  264. /// <summary>
  265. /// The cyan color.
  266. /// </summary>
  267. public const ColorNames Cyan = ColorNames.Cyan;
  268. /// <summary>
  269. /// The red color.
  270. /// </summary>
  271. public const ColorNames Red = ColorNames.Red;
  272. /// <summary>
  273. /// The magenta color.
  274. /// </summary>
  275. public const ColorNames Magenta = ColorNames.Magenta;
  276. /// <summary>
  277. /// The brown color.
  278. /// </summary>
  279. public const ColorNames Brown = ColorNames.Brown;
  280. /// <summary>
  281. /// The gray color.
  282. /// </summary>
  283. public const ColorNames Gray = ColorNames.Gray;
  284. /// <summary>
  285. /// The dark gray color.
  286. /// </summary>
  287. public const ColorNames DarkGray = ColorNames.DarkGray;
  288. /// <summary>
  289. /// The bright bBlue color.
  290. /// </summary>
  291. public const ColorNames BrightBlue = ColorNames.BrightBlue;
  292. /// <summary>
  293. /// The bright green color.
  294. /// </summary>
  295. public const ColorNames BrightGreen = ColorNames.BrightGreen;
  296. /// <summary>
  297. /// The bright cyan color.
  298. /// </summary>
  299. public const ColorNames BrightCyan = ColorNames.BrightCyan;
  300. /// <summary>
  301. /// The bright red color.
  302. /// </summary>
  303. public const ColorNames BrightRed = ColorNames.BrightRed;
  304. /// <summary>
  305. /// The bright magenta color.
  306. /// </summary>
  307. public const ColorNames BrightMagenta = ColorNames.BrightMagenta;
  308. /// <summary>
  309. /// The bright yellow color.
  310. /// </summary>
  311. public const ColorNames BrightYellow = ColorNames.BrightYellow;
  312. /// <summary>
  313. /// The White color.
  314. /// </summary>
  315. public const ColorNames White = ColorNames.White;
  316. #endregion
  317. /// <summary>
  318. /// Converts the provided text to a new <see cref="Color"/> instance.
  319. /// </summary>
  320. /// <param name="text">The text to analyze.</param>
  321. /// <param name="color">The parsed value.</param>
  322. /// <returns>A boolean value indicating whether it was successful.</returns>
  323. public static bool TryParse (string text, [NotNullWhen (true)] out Color color)
  324. {
  325. // empty color
  326. if ((text == null) || (text.Length == 0)) {
  327. color = null;
  328. return false;
  329. }
  330. // #RRGGBB, #RGB
  331. if ((text [0] == '#') && text.Length is 7 or 4) {
  332. if (text.Length == 7) {
  333. var r = Convert.ToInt32 (text.Substring (1, 2), 16);
  334. var g = Convert.ToInt32 (text.Substring (3, 2), 16);
  335. var b = Convert.ToInt32 (text.Substring (5, 2), 16);
  336. color = new Color (r, g, b);
  337. } else {
  338. var rText = char.ToString (text [1]);
  339. var gText = char.ToString (text [2]);
  340. var bText = char.ToString (text [3]);
  341. var r = Convert.ToInt32 (rText + rText, 16);
  342. var g = Convert.ToInt32 (gText + gText, 16);
  343. var b = Convert.ToInt32 (bText + bText, 16);
  344. color = new Color (r, g, b);
  345. }
  346. return true;
  347. }
  348. // #AARRGGBB, #ARGB
  349. if ((text [0] == '#') && text.Length is 8 or 5) {
  350. if (text.Length == 7) {
  351. var a = Convert.ToInt32 (text.Substring (1, 2), 16);
  352. var r = Convert.ToInt32 (text.Substring (3, 2), 16);
  353. var g = Convert.ToInt32 (text.Substring (5, 2), 16);
  354. var b = Convert.ToInt32 (text.Substring (7, 2), 16);
  355. color = new Color (a, r, g, b);
  356. } else {
  357. var aText = char.ToString (text [1]);
  358. var rText = char.ToString (text [2]);
  359. var gText = char.ToString (text [3]);
  360. var bText = char.ToString (text [4]);
  361. var a = Convert.ToInt32 (aText + aText, 16);
  362. var r = Convert.ToInt32 (rText + rText, 16);
  363. var g = Convert.ToInt32 (gText + gText, 16);
  364. var b = Convert.ToInt32 (bText + bText, 16);
  365. color = new Color (a, r, g, b);
  366. }
  367. return true;
  368. }
  369. // rgb(XX,YY,ZZ)
  370. var match = Regex.Match (text, @"rgb\((\d+),(\d+),(\d+)\)");
  371. if (match.Success) {
  372. var r = int.Parse (match.Groups [1].Value);
  373. var g = int.Parse (match.Groups [2].Value);
  374. var b = int.Parse (match.Groups [3].Value);
  375. color = new Color (r, g, b);
  376. return true;
  377. }
  378. // rgb(AA,XX,YY,ZZ)
  379. match = Regex.Match (text, @"rgb\((\d+),(\d+),(\d+),(\d+)\)");
  380. if (match.Success) {
  381. var a = int.Parse (match.Groups [1].Value);
  382. var r = int.Parse (match.Groups [2].Value);
  383. var g = int.Parse (match.Groups [3].Value);
  384. var b = int.Parse (match.Groups [4].Value);
  385. color = new Color (a, r, g, b);
  386. return true;
  387. }
  388. color = null;
  389. return false;
  390. }
  391. #region Operators
  392. /// <summary>
  393. /// Cast from int.
  394. /// </summary>
  395. /// <param name="argb"></param>
  396. public static implicit operator Color (int argb)
  397. {
  398. return new Color (argb);
  399. }
  400. /// <summary>
  401. /// Cast to int.
  402. /// </summary>
  403. /// <param name="color"></param>
  404. public static explicit operator int (Color color)
  405. {
  406. return color.Value;
  407. }
  408. /// <summary>
  409. /// Cast from <see cref="ColorNames"/>.
  410. /// </summary>
  411. /// <param name="colorName"></param>
  412. public static explicit operator Color (ColorNames colorName)
  413. {
  414. return new Color (colorName);
  415. }
  416. /// <summary>
  417. /// Cast to <see cref="ColorNames"/>.
  418. /// </summary>
  419. /// <param name="color"></param>
  420. public static explicit operator ColorNames (Color color)
  421. {
  422. return color.ColorName;
  423. }
  424. /// <summary>
  425. /// Equality operator for two <see cref="Color"/> objects..
  426. /// </summary>
  427. /// <param name="left"></param>
  428. /// <param name="right"></param>
  429. /// <returns></returns>
  430. public static bool operator == (Color left, Color right)
  431. {
  432. return left.Equals (right);
  433. }
  434. /// <summary>
  435. /// Inequality operator for two <see cref="Color"/> objects.
  436. /// </summary>
  437. /// <param name="left"></param>
  438. /// <param name="right"></param>
  439. /// <returns></returns>
  440. public static bool operator != (Color left, Color right)
  441. {
  442. return !left.Equals (right);
  443. }
  444. /// <summary>
  445. /// Equality operator for <see cref="Color"/> and <see cref="ColorNames"/> objects.
  446. /// </summary>
  447. /// <param name="left"></param>
  448. /// <param name="right"></param>
  449. /// <returns></returns>
  450. public static bool operator == (ColorNames left, Color right)
  451. {
  452. return left == right.ColorName;
  453. }
  454. /// <summary>
  455. /// Inequality operator for <see cref="Color"/> and <see cref="ColorNames"/> objects.
  456. /// </summary>
  457. /// <param name="left"></param>
  458. /// <param name="right"></param>
  459. /// <returns></returns>
  460. public static bool operator != (ColorNames left, Color right)
  461. {
  462. return left != right.ColorName;
  463. }
  464. /// <summary>
  465. /// Equality operator for <see cref="Color"/> and <see cref="ColorNames"/> objects.
  466. /// </summary>
  467. /// <param name="left"></param>
  468. /// <param name="right"></param>
  469. /// <returns></returns>
  470. public static bool operator == (Color left, ColorNames right)
  471. {
  472. return left.ColorName == right;
  473. }
  474. /// <summary>
  475. /// Inequality operator for <see cref="Color"/> and <see cref="ColorNames"/> objects.
  476. /// </summary>
  477. /// <param name="left"></param>
  478. /// <param name="right"></param>
  479. /// <returns></returns>
  480. public static bool operator != (Color left, ColorNames right)
  481. {
  482. return left.ColorName != right;
  483. }
  484. /// <inheritdoc/>
  485. public override bool Equals (object obj)
  486. {
  487. return obj is Color other && Equals (other);
  488. }
  489. /// <inheritdoc/>
  490. public bool Equals (Color other)
  491. {
  492. return
  493. A == other.A &&
  494. R == other.R &&
  495. G == other.G &&
  496. B == other.B;
  497. }
  498. /// <inheritdoc/>
  499. public override int GetHashCode ()
  500. {
  501. return HashCode.Combine (A, R, G, B);
  502. }
  503. #endregion
  504. /// <summary>
  505. /// Converts the color to a string representation.
  506. /// </summary>
  507. /// <remarks>
  508. /// If the color is a named color, the name is returned. Otherwise, the color is returned as a hex string.
  509. /// </remarks>
  510. /// <returns></returns>
  511. public override string ToString ()
  512. {
  513. // If Values has an exact match with a named color (in _colorNames), use that.
  514. if (_colorNames.TryGetValue (this, out ColorNames colorName)) {
  515. return Enum.GetName (typeof (ColorNames), colorName);
  516. }
  517. // Otherwise return as an RGB hex value.
  518. return $"#{R:X2}{G:X2}{B:X2}";
  519. }
  520. }
  521. // TODO: Get rid of all the Initialized crap - it's not needed once Curses Driver supports TrueColor
  522. /// <summary>
  523. /// Attributes represent how text is styled when displayed in the terminal.
  524. /// </summary>
  525. /// <remarks>
  526. /// <see cref="Attribute"/> provides a platform independent representation of colors (and someday other forms of text styling).
  527. /// They encode both the foreground and the background color and are used in the <see cref="ColorScheme"/>
  528. /// class to define color schemes that can be used in an application.
  529. /// </remarks>
  530. [JsonConverter (typeof (AttributeJsonConverter))]
  531. public struct Attribute : IEquatable<Attribute> {
  532. /// <summary>
  533. /// Default empty attribute.
  534. /// </summary>
  535. public static readonly Attribute Default = new Attribute (Color.White, Color.Black);
  536. /// <summary>
  537. /// The <see cref="ConsoleDriver"/>-specific color value. If <see cref="Initialized"/> is <see langword="false"/>
  538. /// the value of this property is invalid (typically because the Attribute was created before a driver was loaded)
  539. /// and the attribute should be re-made (see <see cref="Make(Color, Color)"/>) before it is used.
  540. /// </summary>
  541. [JsonIgnore (Condition = JsonIgnoreCondition.Always)]
  542. internal int Value { get; }
  543. /// <summary>
  544. /// The foreground color.
  545. /// </summary>
  546. [JsonConverter (typeof (ColorJsonConverter))]
  547. public Color Foreground { get; private init; }
  548. /// <summary>
  549. /// The background color.
  550. /// </summary>
  551. [JsonConverter (typeof (ColorJsonConverter))]
  552. public Color Background { get; private init; }
  553. /// <summary>
  554. /// Initializes a new instance with default values.
  555. /// </summary>
  556. public Attribute ()
  557. {
  558. var d = Default;
  559. Value = -1;
  560. Foreground = d.Foreground;
  561. Background = d.Background;
  562. }
  563. /// <summary>
  564. /// Initializes a new instance with platform specific color value.
  565. /// </summary>
  566. /// <param name="platformColor">Value.</param>
  567. internal Attribute (int platformColor) : this (platformColor, Default.Foreground, Default.Background) { }
  568. /// <summary>
  569. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  570. /// </summary>
  571. /// <param name="platformColor">platform-dependent color value.</param>
  572. /// <param name="foreground">Foreground</param>
  573. /// <param name="background">Background</param>
  574. internal Attribute (int platformColor, Color foreground, Color background)
  575. {
  576. Foreground = foreground;
  577. Background = background;
  578. Value = platformColor;
  579. Initialized = true;
  580. }
  581. /// <summary>
  582. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  583. /// </summary>
  584. /// <param name="platformColor">platform-dependent color value.</param>
  585. /// <param name="foreground">Foreground</param>
  586. /// <param name="background">Background</param>
  587. internal Attribute (int platformColor, ColorNames foreground, ColorNames background) : this (platformColor, (Color)foreground, (Color)background) { }
  588. /// <summary>
  589. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  590. /// </summary>
  591. /// <param name="foreground">Foreground</param>
  592. /// <param name="background">Background</param>
  593. public Attribute (Color foreground, Color background)
  594. {
  595. Foreground = foreground;
  596. Background = background;
  597. if (Application.Driver == null) {
  598. // Create the attribute, but show it's not been initialized
  599. Initialized = false;
  600. Value = -1;
  601. return;
  602. }
  603. var make = Application.Driver.MakeAttribute (foreground, background);
  604. Initialized = make.Initialized;
  605. Value = make.Value;
  606. }
  607. /// <summary>
  608. /// Initializes a new instance with a <see cref="ColorNames"/> value. Both <see cref="Foreground"/> and
  609. /// <see cref="Background"/> will be set to the specified color.
  610. /// </summary>
  611. /// <param name="colorName">Value.</param>
  612. internal Attribute (ColorNames colorName) : this (colorName, colorName) { }
  613. /// <summary>
  614. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  615. /// </summary>
  616. /// <param name="foregroundName">Foreground</param>
  617. /// <param name="backgroundName">Background</param>
  618. public Attribute (ColorNames foregroundName, ColorNames backgroundName) : this (new Color (foregroundName), new Color (backgroundName)) { }
  619. /// <summary>
  620. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  621. /// </summary>
  622. /// <param name="foregroundName">Foreground</param>
  623. /// <param name="background">Background</param>
  624. public Attribute (ColorNames foregroundName, Color background) : this (new Color (foregroundName), background) { }
  625. /// <summary>
  626. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  627. /// </summary>
  628. /// <param name="foreground">Foreground</param>
  629. /// <param name="backgroundName">Background</param>
  630. public Attribute (Color foreground, ColorNames backgroundName) : this (foreground, new Color (backgroundName)) { }
  631. /// <summary>
  632. /// Initializes a new instance of the <see cref="Attribute"/> struct
  633. /// with the same colors for the foreground and background.
  634. /// </summary>
  635. /// <param name="color">The color.</param>
  636. public Attribute (Color color) : this (color, color) { }
  637. /// <summary>
  638. /// Compares two attributes for equality.
  639. /// </summary>
  640. /// <param name="left"></param>
  641. /// <param name="right"></param>
  642. /// <returns></returns>
  643. public static bool operator == (Attribute left, Attribute right) => left.Equals (right);
  644. /// <summary>
  645. /// Compares two attributes for inequality.
  646. /// </summary>
  647. /// <param name="left"></param>
  648. /// <param name="right"></param>
  649. /// <returns></returns>
  650. public static bool operator != (Attribute left, Attribute right) => !(left == right);
  651. /// <inheritdoc />
  652. public override bool Equals (object obj)
  653. {
  654. return obj is Attribute other && Equals (other);
  655. }
  656. /// <inheritdoc />
  657. public bool Equals (Attribute other)
  658. {
  659. return Value == other.Value &&
  660. Foreground == other.Foreground &&
  661. Background == other.Background;
  662. }
  663. /// <inheritdoc />
  664. public override int GetHashCode () => HashCode.Combine (Value, Foreground, Background);
  665. /// <summary>
  666. /// If <see langword="true"/> the attribute has been initialized by a <see cref="ConsoleDriver"/> and
  667. /// thus has <see cref="Value"/> that is valid for that driver. If <see langword="false"/> the <see cref="Foreground"/>
  668. /// and <see cref="Background"/> colors may have been set '-1' but
  669. /// the attribute has not been mapped to a <see cref="ConsoleDriver"/> specific color value.
  670. /// </summary>
  671. /// <remarks>
  672. /// Attributes that have not been initialized must eventually be initialized before being passed to a driver.
  673. /// </remarks>
  674. [JsonIgnore]
  675. public bool Initialized { get; internal set; }
  676. /// <summary>
  677. /// Returns <see langword="true"/> if the Attribute is valid (both foreground and background have valid color values).
  678. /// </summary>
  679. /// <returns></returns>
  680. [JsonIgnore]
  681. public bool HasValidColors => (int)Foreground.ColorName > -1 && (int)Background.ColorName > -1;
  682. /// <inheritdoc />
  683. public override string ToString ()
  684. {
  685. // Note, Unit tests are dependent on this format
  686. return $"{Foreground},{Background}";
  687. }
  688. }
  689. /// <summary>
  690. /// Defines the color <see cref="Attribute"/>s for common visible elements in a <see cref="View"/>.
  691. /// Containers such as <see cref="Window"/> and <see cref="FrameView"/> use <see cref="ColorScheme"/> to determine
  692. /// the colors used by sub-views.
  693. /// </summary>
  694. /// <remarks>
  695. /// See also: <see cref="Colors.ColorSchemes"/>.
  696. /// </remarks>
  697. [JsonConverter (typeof (ColorSchemeJsonConverter))]
  698. public class ColorScheme : IEquatable<ColorScheme> {
  699. Attribute _normal = Attribute.Default;
  700. Attribute _focus = Attribute.Default;
  701. Attribute _hotNormal = Attribute.Default;
  702. Attribute _hotFocus = Attribute.Default;
  703. Attribute _disabled = Attribute.Default;
  704. /// <summary>
  705. /// Used by <see cref="Colors.SetColorScheme(ColorScheme, string)"/> and <see cref="Colors.GetColorScheme(string)"/> to track which ColorScheme
  706. /// is being accessed.
  707. /// </summary>
  708. internal string schemeBeingSet = "";
  709. /// <summary>
  710. /// Creates a new instance.
  711. /// </summary>
  712. public ColorScheme () : this (Attribute.Default) { }
  713. /// <summary>
  714. /// Creates a new instance, initialized with the values from <paramref name="scheme"/>.
  715. /// </summary>
  716. /// <param name="scheme">The scheme to initialize the new instance with.</param>
  717. public ColorScheme (ColorScheme scheme) : base ()
  718. {
  719. if (scheme != null) {
  720. _normal = scheme.Normal;
  721. _focus = scheme.Focus;
  722. _hotNormal = scheme.HotNormal;
  723. _disabled = scheme.Disabled;
  724. _hotFocus = scheme.HotFocus;
  725. }
  726. }
  727. /// <summary>
  728. /// Creates a new instance, initialized with the values from <paramref name="attribute"/>.
  729. /// </summary>
  730. /// <param name="attribute">The attribute to initialize the new instance with.</param>
  731. public ColorScheme (Attribute attribute)
  732. {
  733. _normal = attribute;
  734. _focus = attribute;
  735. _hotNormal = attribute;
  736. _disabled = attribute;
  737. _hotFocus = attribute;
  738. }
  739. /// <summary>
  740. /// The foreground and background color for text when the view is not focused, hot, or disabled.
  741. /// </summary>
  742. public Attribute Normal {
  743. get { return _normal; }
  744. set {
  745. if (!value.HasValidColors) {
  746. return;
  747. }
  748. _normal = value;
  749. }
  750. }
  751. /// <summary>
  752. /// The foreground and background color for text when the view has the focus.
  753. /// </summary>
  754. public Attribute Focus {
  755. get { return _focus; }
  756. set {
  757. if (!value.HasValidColors) {
  758. return;
  759. }
  760. _focus = value;
  761. }
  762. }
  763. /// <summary>
  764. /// The foreground and background color for text when the view is highlighted (hot).
  765. /// </summary>
  766. public Attribute HotNormal {
  767. get { return _hotNormal; }
  768. set {
  769. if (!value.HasValidColors) {
  770. return;
  771. }
  772. _hotNormal = value;
  773. }
  774. }
  775. /// <summary>
  776. /// The foreground and background color for text when the view is highlighted (hot) and has focus.
  777. /// </summary>
  778. public Attribute HotFocus {
  779. get { return _hotFocus; }
  780. set {
  781. if (!value.HasValidColors) {
  782. return;
  783. }
  784. _hotFocus = value;
  785. }
  786. }
  787. /// <summary>
  788. /// The default foreground and background color for text, when the view is disabled.
  789. /// </summary>
  790. public Attribute Disabled {
  791. get { return _disabled; }
  792. set {
  793. if (!value.HasValidColors) {
  794. return;
  795. }
  796. _disabled = value;
  797. }
  798. }
  799. /// <summary>
  800. /// Compares two <see cref="ColorScheme"/> objects for equality.
  801. /// </summary>
  802. /// <param name="obj"></param>
  803. /// <returns>true if the two objects are equal</returns>
  804. public override bool Equals (object obj)
  805. {
  806. return Equals (obj as ColorScheme);
  807. }
  808. /// <summary>
  809. /// Compares two <see cref="ColorScheme"/> objects for equality.
  810. /// </summary>
  811. /// <param name="other"></param>
  812. /// <returns>true if the two objects are equal</returns>
  813. public bool Equals (ColorScheme other)
  814. {
  815. return other != null &&
  816. EqualityComparer<Attribute>.Default.Equals (_normal, other._normal) &&
  817. EqualityComparer<Attribute>.Default.Equals (_focus, other._focus) &&
  818. EqualityComparer<Attribute>.Default.Equals (_hotNormal, other._hotNormal) &&
  819. EqualityComparer<Attribute>.Default.Equals (_hotFocus, other._hotFocus) &&
  820. EqualityComparer<Attribute>.Default.Equals (_disabled, other._disabled);
  821. }
  822. /// <summary>
  823. /// Returns a hashcode for this instance.
  824. /// </summary>
  825. /// <returns>hashcode for this instance</returns>
  826. public override int GetHashCode ()
  827. {
  828. int hashCode = -1242460230;
  829. hashCode = hashCode * -1521134295 + _normal.GetHashCode ();
  830. hashCode = hashCode * -1521134295 + _focus.GetHashCode ();
  831. hashCode = hashCode * -1521134295 + _hotNormal.GetHashCode ();
  832. hashCode = hashCode * -1521134295 + _hotFocus.GetHashCode ();
  833. hashCode = hashCode * -1521134295 + _disabled.GetHashCode ();
  834. return hashCode;
  835. }
  836. /// <summary>
  837. /// Compares two <see cref="ColorScheme"/> objects for equality.
  838. /// </summary>
  839. /// <param name="left"></param>
  840. /// <param name="right"></param>
  841. /// <returns><c>true</c> if the two objects are equivalent</returns>
  842. public static bool operator == (ColorScheme left, ColorScheme right)
  843. {
  844. return EqualityComparer<ColorScheme>.Default.Equals (left, right);
  845. }
  846. /// <summary>
  847. /// Compares two <see cref="ColorScheme"/> objects for inequality.
  848. /// </summary>
  849. /// <param name="left"></param>
  850. /// <param name="right"></param>
  851. /// <returns><c>true</c> if the two objects are not equivalent</returns>
  852. public static bool operator != (ColorScheme left, ColorScheme right)
  853. {
  854. return !(left == right);
  855. }
  856. internal void Initialize ()
  857. {
  858. // If the new scheme was created before a driver was loaded, we need to re-make
  859. // the attributes
  860. if (!_normal.Initialized) {
  861. _normal = new Attribute (_normal.Foreground, _normal.Background);
  862. }
  863. if (!_focus.Initialized) {
  864. _focus = new Attribute (_focus.Foreground, _focus.Background);
  865. }
  866. if (!_hotNormal.Initialized) {
  867. _hotNormal = new Attribute (_hotNormal.Foreground, _hotNormal.Background);
  868. }
  869. if (!_hotFocus.Initialized) {
  870. _hotFocus = new Attribute (_hotFocus.Foreground, _hotFocus.Background);
  871. }
  872. if (!_disabled.Initialized) {
  873. _disabled = new Attribute (_disabled.Foreground, _disabled.Background);
  874. }
  875. }
  876. }
  877. /// <summary>
  878. /// The default <see cref="ColorScheme"/>s for the application.
  879. /// </summary>
  880. /// <remarks>
  881. /// This property can be set in a Theme to change the default <see cref="Colors"/> for the application.
  882. /// </remarks>
  883. public static class Colors {
  884. private class SchemeNameComparerIgnoreCase : IEqualityComparer<string> {
  885. public bool Equals (string x, string y)
  886. {
  887. if (x != null && y != null) {
  888. return string.Equals (x, y, StringComparison.InvariantCultureIgnoreCase);
  889. }
  890. return false;
  891. }
  892. public int GetHashCode (string obj)
  893. {
  894. return obj.ToLowerInvariant ().GetHashCode ();
  895. }
  896. }
  897. static Colors ()
  898. {
  899. ColorSchemes = Create ();
  900. }
  901. /// <summary>
  902. /// Creates a new dictionary of new <see cref="ColorScheme"/> objects.
  903. /// </summary>
  904. public static Dictionary<string, ColorScheme> Create ()
  905. {
  906. // Use reflection to dynamically create the default set of ColorSchemes from the list defined
  907. // by the class.
  908. return typeof (Colors).GetProperties ()
  909. .Where (p => p.PropertyType == typeof (ColorScheme))
  910. .Select (p => new KeyValuePair<string, ColorScheme> (p.Name, new ColorScheme ()))
  911. .ToDictionary (t => t.Key, t => t.Value, comparer: new SchemeNameComparerIgnoreCase ());
  912. }
  913. /// <summary>
  914. /// The application Toplevel color scheme, for the default Toplevel views.
  915. /// </summary>
  916. /// <remarks>
  917. /// <para>
  918. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["TopLevel"];</c>
  919. /// </para>
  920. /// </remarks>
  921. public static ColorScheme TopLevel { get => GetColorScheme (); set => SetColorScheme (value); }
  922. /// <summary>
  923. /// The base color scheme, for the default Toplevel views.
  924. /// </summary>
  925. /// <remarks>
  926. /// <para>
  927. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Base"];</c>
  928. /// </para>
  929. /// </remarks>
  930. public static ColorScheme Base { get => GetColorScheme (); set => SetColorScheme (value); }
  931. /// <summary>
  932. /// The dialog color scheme, for standard popup dialog boxes
  933. /// </summary>
  934. /// <remarks>
  935. /// <para>
  936. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Dialog"];</c>
  937. /// </para>
  938. /// </remarks>
  939. public static ColorScheme Dialog { get => GetColorScheme (); set => SetColorScheme (value); }
  940. /// <summary>
  941. /// The menu bar color
  942. /// </summary>
  943. /// <remarks>
  944. /// <para>
  945. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Menu"];</c>
  946. /// </para>
  947. /// </remarks>
  948. public static ColorScheme Menu { get => GetColorScheme (); set => SetColorScheme (value); }
  949. /// <summary>
  950. /// The color scheme for showing errors.
  951. /// </summary>
  952. /// <remarks>
  953. /// <para>
  954. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Error"];</c>
  955. /// </para>
  956. /// </remarks>
  957. public static ColorScheme Error { get => GetColorScheme (); set => SetColorScheme (value); }
  958. static ColorScheme GetColorScheme ([CallerMemberName] string schemeBeingSet = null)
  959. {
  960. return ColorSchemes [schemeBeingSet];
  961. }
  962. static void SetColorScheme (ColorScheme colorScheme, [CallerMemberName] string schemeBeingSet = null)
  963. {
  964. ColorSchemes [schemeBeingSet] = colorScheme;
  965. colorScheme.schemeBeingSet = schemeBeingSet;
  966. }
  967. /// <summary>
  968. /// Provides the defined <see cref="ColorScheme"/>s.
  969. /// </summary>
  970. [SerializableConfigurationProperty (Scope = typeof (ThemeScope), OmitClassName = true)]
  971. [JsonConverter (typeof (DictionaryJsonConverter<ColorScheme>))]
  972. public static Dictionary<string, ColorScheme> ColorSchemes { get; private set; }
  973. }
  974. }