Color.cs 31 KB

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