Color.cs 33 KB

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