Color.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #nullable enable
  2. using System.Collections.Frozen;
  3. using System.Diagnostics.Contracts;
  4. using System.Drawing;
  5. using System.Globalization;
  6. using System.Numerics;
  7. using System.Runtime.CompilerServices;
  8. using System.Runtime.InteropServices;
  9. using System.Text.Json.Serialization;
  10. using ColorHelper;
  11. namespace Terminal.Gui;
  12. /// <summary>
  13. /// Represents a 24-bit color encoded in ARGB32 format.
  14. /// <para/>
  15. /// </summary>
  16. /// <seealso cref="Attribute"/>
  17. /// <seealso cref="ColorExtensions"/>
  18. /// <seealso cref="ColorName"/>
  19. [JsonConverter (typeof (ColorJsonConverter))]
  20. [StructLayout (LayoutKind.Explicit)]
  21. public readonly partial record struct Color : ISpanParsable<Color>, IUtf8SpanParsable<Color>, ISpanFormattable,
  22. IUtf8SpanFormattable, IMinMaxValue<Color>
  23. {
  24. /// <summary>The value of the alpha channel component</summary>
  25. /// <remarks>
  26. /// The alpha channel is not currently supported, so the value of the alpha channel bits will not affect
  27. /// rendering.
  28. /// </remarks>
  29. [JsonIgnore]
  30. [field: FieldOffset (3)]
  31. public readonly byte A;
  32. /// <summary>The value of this <see cref="Color"/> as a <see langword="uint"/> in ARGB32 format.</summary>
  33. /// <remarks>
  34. /// The alpha channel is not currently supported, so the value of the alpha channel bits will not affect
  35. /// rendering.
  36. /// </remarks>
  37. [JsonIgnore]
  38. [field: FieldOffset (0)]
  39. public readonly uint Argb;
  40. /// <summary>The value of the blue color component.</summary>
  41. [JsonIgnore]
  42. [field: FieldOffset (0)]
  43. public readonly byte B;
  44. /// <summary>The value of the green color component.</summary>
  45. [JsonIgnore]
  46. [field: FieldOffset (1)]
  47. public readonly byte G;
  48. /// <summary>The value of the red color component.</summary>
  49. [JsonIgnore]
  50. [field: FieldOffset (2)]
  51. public readonly byte R;
  52. /// <summary>The value of this <see cref="Color"/> encoded as a signed 32-bit integer in ARGB32 format.</summary>
  53. [JsonIgnore]
  54. [field: FieldOffset (0)]
  55. public readonly int Rgba;
  56. /// <summary>
  57. /// Initializes a new instance of the <see cref="Color"/> <see langword="struct"/> using the supplied component
  58. /// values.
  59. /// </summary>
  60. /// <param name="red">The red 8-bits.</param>
  61. /// <param name="green">The green 8-bits.</param>
  62. /// <param name="blue">The blue 8-bits.</param>
  63. /// <param name="alpha">Optional; defaults to 0xFF. The Alpha channel is not supported by Terminal.Gui.</param>
  64. /// <remarks>Alpha channel is not currently supported by Terminal.Gui.</remarks>
  65. /// <exception cref="OverflowException">If the value of any parameter is greater than <see cref="byte.MaxValue"/>.</exception>
  66. /// <exception cref="ArgumentOutOfRangeException">If the value of any parameter is negative.</exception>
  67. public Color (int red = 0, int green = 0, int blue = 0, int alpha = byte.MaxValue)
  68. {
  69. ArgumentOutOfRangeException.ThrowIfNegative (red, nameof (red));
  70. ArgumentOutOfRangeException.ThrowIfNegative (green, nameof (green));
  71. ArgumentOutOfRangeException.ThrowIfNegative (blue, nameof (blue));
  72. ArgumentOutOfRangeException.ThrowIfNegative (alpha, nameof (alpha));
  73. A = Convert.ToByte (alpha);
  74. R = Convert.ToByte (red);
  75. G = Convert.ToByte (green);
  76. B = Convert.ToByte (blue);
  77. }
  78. /// <summary>
  79. /// Initializes a new instance of the <see cref="Color"/> class with an encoded signed 32-bit color value in
  80. /// ARGB32 format.
  81. /// </summary>
  82. /// <param name="rgba">The encoded 32-bit color value (see <see cref="Rgba"/>).</param>
  83. /// <remarks>
  84. /// The alpha channel is not currently supported, so the value of the alpha channel bits will not affect
  85. /// rendering.
  86. /// </remarks>
  87. public Color (int rgba) { Rgba = rgba; }
  88. /// <summary>
  89. /// Initializes a new instance of the <see cref="Color"/> class with an encoded unsigned 32-bit color value in
  90. /// ARGB32 format.
  91. /// </summary>
  92. /// <param name="argb">The encoded unsigned 32-bit color value (see <see cref="Argb"/>).</param>
  93. /// <remarks>
  94. /// The alpha channel is not currently supported, so the value of the alpha channel bits will not affect
  95. /// rendering.
  96. /// </remarks>
  97. public Color (uint argb) { Argb = argb; }
  98. /// <summary>Initializes a new instance of the <see cref="Color"/> color from a legacy 16-color named value.</summary>
  99. /// <param name="colorName">The 16-color value.</param>
  100. public Color (in ColorName colorName) { this = ColorExtensions.ColorNameToColorMap [colorName]; }
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="Color"/> color from string. See
  103. /// <see cref="TryParse(string, out Color?)"/> for details.
  104. /// </summary>
  105. /// <param name="colorString"></param>
  106. /// <exception cref="ArgumentNullException">If <paramref name="colorString"/> is <see langword="null"/>.</exception>
  107. /// <exception cref="ArgumentException">
  108. /// If <paramref name="colorString"/> is an empty string or consists of only whitespace
  109. /// characters.
  110. /// </exception>
  111. /// <exception cref="ColorParseException">If thrown by <see cref="Parse(string?,System.IFormatProvider?)"/></exception>
  112. public Color (string colorString)
  113. {
  114. ArgumentException.ThrowIfNullOrWhiteSpace (colorString, nameof (colorString));
  115. this = Parse (colorString, CultureInfo.InvariantCulture);
  116. }
  117. /// <summary>Initializes a new instance of the <see cref="Color"/> with all channels set to 0.</summary>
  118. public Color () { Argb = 0u; }
  119. /// <summary>Gets or sets the 3-byte/6-character hexadecimal value for each of the legacy 16-color values.</summary>
  120. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true)]
  121. public static Dictionary<ColorName, string> Colors
  122. {
  123. get =>
  124. // Transform _colorToNameMap into a Dictionary<ColorNames,string>
  125. ColorExtensions.ColorToNameMap.ToDictionary (static kvp => kvp.Value, static kvp => kvp.Key.ToString ("g"));
  126. set
  127. {
  128. // Transform Dictionary<ColorNames,string> into _colorToNameMap
  129. ColorExtensions.ColorToNameMap = value.ToFrozenDictionary (GetColorToNameMapKey, GetColorToNameMapValue);
  130. return;
  131. static Color GetColorToNameMapKey (KeyValuePair<ColorName, string> kvp) { return new Color (kvp.Value); }
  132. static ColorName GetColorToNameMapValue (KeyValuePair<ColorName, string> kvp)
  133. {
  134. return Enum.TryParse (kvp.Key.ToString (), true, out ColorName colorName)
  135. ? colorName
  136. : throw new ArgumentException ($"Invalid color name: {kvp.Key}");
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Gets the <see cref="Color"/> using a legacy 16-color <see cref="ColorName"/> value. <see langword="get"/> will
  142. /// return the closest 16 color match to the true color when no exact value is found.
  143. /// </summary>
  144. /// <remarks>
  145. /// Get returns the <see cref="GetClosestNamedColor (Color)"/> of the closest 24-bit color value. Set sets the RGB
  146. /// value using a hard-coded map.
  147. /// </remarks>
  148. public AnsiColorCode GetAnsiColorCode () { return ColorExtensions.ColorNameToAnsiColorMap [GetClosestNamedColor ()]; }
  149. /// <summary>
  150. /// Gets the <see cref="Color"/> using a legacy 16-color <see cref="Gui.ColorName"/> value. <see langword="get"/>
  151. /// will return the closest 16 color match to the true color when no exact value is found.
  152. /// </summary>
  153. /// <remarks>
  154. /// Get returns the <see cref="GetClosestNamedColor (Color)"/> of the closest 24-bit color value. Set sets the RGB
  155. /// value using a hard-coded map.
  156. /// </remarks>
  157. public ColorName GetClosestNamedColor () { return GetClosestNamedColor (this); }
  158. /// <summary>
  159. /// Determines if the closest named <see cref="Color"/> to <see langword="this"/> is the provided
  160. /// <paramref name="namedColor"/>.
  161. /// </summary>
  162. /// <param name="namedColor">
  163. /// The <see cref="GetClosestNamedColor (Color)"/> to check if this <see cref="Color"/> is closer
  164. /// to than any other configured named color.
  165. /// </param>
  166. /// <returns>
  167. /// <see langword="true"/> if the closest named color is the provided value. <br/> <see langword="false"/> if any
  168. /// other named color is closer to this <see cref="Color"/> than <paramref name="namedColor"/>.
  169. /// </returns>
  170. /// <remarks>
  171. /// If <see langword="this"/> is equidistant from two named colors, the result of this method is not guaranteed to
  172. /// be determinate.
  173. /// </remarks>
  174. [Pure]
  175. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  176. public bool IsClosestToNamedColor (in ColorName namedColor) { return GetClosestNamedColor () == namedColor; }
  177. /// <summary>
  178. /// Determines if the closest named <see cref="Color"/> to <paramref name="color"/>/> is the provided
  179. /// <paramref name="namedColor"/>.
  180. /// </summary>
  181. /// <param name="color">
  182. /// The color to test against the <see cref="GetClosestNamedColor (Color)"/> value in
  183. /// <paramref name="namedColor"/>.
  184. /// </param>
  185. /// <param name="namedColor">
  186. /// The <see cref="GetClosestNamedColor (Color)"/> to check if this <see cref="Color"/> is closer
  187. /// to than any other configured named color.
  188. /// </param>
  189. /// <returns>
  190. /// <see langword="true"/> if the closest named color to <paramref name="color"/> is the provided value. <br/>
  191. /// <see langword="false"/> if any other named color is closer to <paramref name="color"/> than
  192. /// <paramref name="namedColor"/>.
  193. /// </returns>
  194. /// <remarks>
  195. /// If <paramref name="color"/> is equidistant from two named colors, the result of this method is not guaranteed
  196. /// to be determinate.
  197. /// </remarks>
  198. [Pure]
  199. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  200. public static bool IsColorClosestToNamedColor (in Color color, in ColorName namedColor) { return color.IsClosestToNamedColor (in namedColor); }
  201. /// <summary>Gets the "closest" named color to this <see cref="Color"/> value.</summary>
  202. /// <param name="inputColor"></param>
  203. /// <remarks>
  204. /// Distance is defined here as the Euclidean distance between each color interpreted as a <see cref="Vector3"/>.
  205. /// <para/>
  206. /// The order of the values in the passed Vector3 must be
  207. /// </remarks>
  208. /// <returns></returns>
  209. [SkipLocalsInit]
  210. internal static ColorName GetClosestNamedColor (Color inputColor)
  211. {
  212. return ColorExtensions.ColorToNameMap.MinBy (pair => CalculateColorDistance (inputColor, pair.Key)).Value;
  213. }
  214. [SkipLocalsInit]
  215. private static float CalculateColorDistance (in Vector4 color1, in Vector4 color2) { return Vector4.Distance (color1, color2); }
  216. /// <summary>
  217. /// Gets a color that is the same hue as the current color, but with a different lightness.
  218. /// </summary>
  219. /// <returns></returns>
  220. public Color GetHighlightColor ()
  221. {
  222. // TODO: This is a temporary implementation; just enough to show how it could work.
  223. var hsl = ColorHelper.ColorConverter.RgbToHsl(new RGB (R, G, B));
  224. var amount = .7;
  225. if (hsl.L <= 5)
  226. {
  227. return DarkGray;
  228. }
  229. hsl.L = (byte)(hsl.L * amount);
  230. var rgb = ColorHelper.ColorConverter.HslToRgb (hsl);
  231. return new (rgb.R, rgb.G, rgb.B);
  232. }
  233. /// <summary>
  234. /// Gets a color that is the same hue as the current color, but with a different lightness.
  235. /// </summary>
  236. /// <returns></returns>
  237. public Color GetDarkerColor ()
  238. {
  239. // TODO: This is a temporary implementation; just enough to show how it could work.
  240. var hsl = ColorHelper.ColorConverter.RgbToHsl (new RGB (R, G, B));
  241. var amount = .3;
  242. if (hsl.L <= 5)
  243. {
  244. return DarkGray;
  245. }
  246. hsl.L = (byte)(hsl.L * amount);
  247. var rgb = ColorHelper.ColorConverter.HslToRgb (hsl);
  248. return new (rgb.R, rgb.G, rgb.B);
  249. }
  250. #region Legacy Color Names
  251. /// <summary>The black color.</summary>
  252. public const ColorName Black = ColorName.Black;
  253. /// <summary>The blue color.</summary>
  254. public const ColorName Blue = ColorName.Blue;
  255. /// <summary>The green color.</summary>
  256. public const ColorName Green = ColorName.Green;
  257. /// <summary>The cyan color.</summary>
  258. public const ColorName Cyan = ColorName.Cyan;
  259. /// <summary>The red color.</summary>
  260. public const ColorName Red = ColorName.Red;
  261. /// <summary>The magenta color.</summary>
  262. public const ColorName Magenta = ColorName.Magenta;
  263. /// <summary>The yellow color.</summary>
  264. public const ColorName Yellow = ColorName.Yellow;
  265. /// <summary>The gray color.</summary>
  266. public const ColorName Gray = ColorName.Gray;
  267. /// <summary>The dark gray color.</summary>
  268. public const ColorName DarkGray = ColorName.DarkGray;
  269. /// <summary>The bright bBlue color.</summary>
  270. public const ColorName BrightBlue = ColorName.BrightBlue;
  271. /// <summary>The bright green color.</summary>
  272. public const ColorName BrightGreen = ColorName.BrightGreen;
  273. /// <summary>The bright cyan color.</summary>
  274. public const ColorName BrightCyan = ColorName.BrightCyan;
  275. /// <summary>The bright red color.</summary>
  276. public const ColorName BrightRed = ColorName.BrightRed;
  277. /// <summary>The bright magenta color.</summary>
  278. public const ColorName BrightMagenta = ColorName.BrightMagenta;
  279. /// <summary>The bright yellow color.</summary>
  280. public const ColorName BrightYellow = ColorName.BrightYellow;
  281. /// <summary>The White color.</summary>
  282. public const ColorName White = ColorName.White;
  283. #endregion
  284. }