Color.cs 33 KB

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