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="ColorName16"/>
  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 ColorName16 colorName) { this = ColorExtensions.ColorName16ToColorMap [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. // TODO: ColorName and AnsiColorCode are only needed when a driver is in Force16Color mode and we
  120. // TODO: should be able to remove these from any non-Driver-specific usages.
  121. /// <summary>Gets or sets the 3-byte/6-character hexadecimal value for each of the legacy 16-color values.</summary>
  122. [SerializableConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true)]
  123. public static Dictionary<ColorName16, string> Colors16
  124. {
  125. get =>
  126. // Transform _colorToNameMap into a Dictionary<ColorNames,string>
  127. ColorExtensions.ColorToName16Map.ToDictionary (static kvp => kvp.Value, static kvp => kvp.Key.ToString ("g"));
  128. set
  129. {
  130. // Transform Dictionary<ColorNames,string> into _colorToNameMap
  131. ColorExtensions.ColorToName16Map = value.ToFrozenDictionary (GetColorToNameMapKey, GetColorToNameMapValue);
  132. return;
  133. static Color GetColorToNameMapKey (KeyValuePair<ColorName16, string> kvp) { return new Color (kvp.Value); }
  134. static ColorName16 GetColorToNameMapValue (KeyValuePair<ColorName16, string> kvp)
  135. {
  136. return Enum.TryParse (kvp.Key.ToString (), true, out ColorName16 colorName)
  137. ? colorName
  138. : throw new ArgumentException ($"Invalid color name: {kvp.Key}");
  139. }
  140. }
  141. }
  142. /// <summary>
  143. /// Gets the <see cref="Color"/> using a legacy 16-color <see cref="ColorName16"/> value. <see langword="get"/> will
  144. /// return the closest 16 color match to the true color when no exact value is found.
  145. /// </summary>
  146. /// <remarks>
  147. /// Get returns the <see cref="GetClosestNamedColor16(Color)"/> of the closest 24-bit color value. Set sets the RGB
  148. /// value using a hard-coded map.
  149. /// </remarks>
  150. public AnsiColorCode GetAnsiColorCode () { return ColorExtensions.ColorName16ToAnsiColorMap [GetClosestNamedColor16 ()]; }
  151. /// <summary>
  152. /// Gets the <see cref="Color"/> using a legacy 16-color <see cref="ColorName16"/> value. <see langword="get"/>
  153. /// will return the closest 16 color match to the true color when no exact value is found.
  154. /// </summary>
  155. /// <remarks>
  156. /// Get returns the <see cref="GetClosestNamedColor16(Terminal.Gui.Color)"/> of the closest 24-bit color value. Set sets the RGB
  157. /// value using a hard-coded map.
  158. /// </remarks>
  159. public ColorName16 GetClosestNamedColor16 () { return GetClosestNamedColor16 (this); }
  160. /// <summary>
  161. /// Determines if the closest named <see cref="Color"/> to <see langword="this"/> is the provided
  162. /// <paramref name="namedColor"/>.
  163. /// </summary>
  164. /// <param name="namedColor">
  165. /// The <see cref="GetClosestNamedColor16(Terminal.Gui.Color)"/> to check if this <see cref="Color"/> is closer
  166. /// to than any other configured named color.
  167. /// </param>
  168. /// <returns>
  169. /// <see langword="true"/> if the closest named color is the provided value. <br/> <see langword="false"/> if any
  170. /// other named color is closer to this <see cref="Color"/> than <paramref name="namedColor"/>.
  171. /// </returns>
  172. /// <remarks>
  173. /// If <see langword="this"/> is equidistant from two named colors, the result of this method is not guaranteed to
  174. /// be determinate.
  175. /// </remarks>
  176. [Pure]
  177. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  178. public bool IsClosestToNamedColor16 (in ColorName16 namedColor) { return GetClosestNamedColor16 () == namedColor; }
  179. /// <summary>
  180. /// Determines if the closest named <see cref="Color"/> to <paramref name="color"/>/> is the provided
  181. /// <paramref name="namedColor"/>.
  182. /// </summary>
  183. /// <param name="color">
  184. /// The color to test against the <see cref="GetClosestNamedColor16(Terminal.Gui.Color)"/> value in
  185. /// <paramref name="namedColor"/>.
  186. /// </param>
  187. /// <param name="namedColor">
  188. /// The <see cref="GetClosestNamedColor16(Terminal.Gui.Color)"/> to check if this <see cref="Color"/> is closer
  189. /// to than any other configured named color.
  190. /// </param>
  191. /// <returns>
  192. /// <see langword="true"/> if the closest named color to <paramref name="color"/> is the provided value. <br/>
  193. /// <see langword="false"/> if any other named color is closer to <paramref name="color"/> than
  194. /// <paramref name="namedColor"/>.
  195. /// </returns>
  196. /// <remarks>
  197. /// If <paramref name="color"/> is equidistant from two named colors, the result of this method is not guaranteed
  198. /// to be determinate.
  199. /// </remarks>
  200. [Pure]
  201. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  202. public static bool IsColorClosestToNamedColor16 (in Color color, in ColorName16 namedColor) { return color.IsClosestToNamedColor16 (in namedColor); }
  203. /// <summary>Gets the "closest" named color to this <see cref="Color"/> value.</summary>
  204. /// <param name="inputColor"></param>
  205. /// <remarks>
  206. /// Distance is defined here as the Euclidean distance between each color interpreted as a <see cref="Vector3"/>.
  207. /// </remarks>
  208. /// <returns></returns>
  209. [SkipLocalsInit]
  210. internal static ColorName16 GetClosestNamedColor16 (Color inputColor)
  211. {
  212. return ColorExtensions.ColorToName16Map.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 ColorName16 Black = ColorName16.Black;
  253. /// <summary>The blue color.</summary>
  254. public const ColorName16 Blue = ColorName16.Blue;
  255. /// <summary>The green color.</summary>
  256. public const ColorName16 Green = ColorName16.Green;
  257. /// <summary>The cyan color.</summary>
  258. public const ColorName16 Cyan = ColorName16.Cyan;
  259. /// <summary>The red color.</summary>
  260. public const ColorName16 Red = ColorName16.Red;
  261. /// <summary>The magenta color.</summary>
  262. public const ColorName16 Magenta = ColorName16.Magenta;
  263. /// <summary>The yellow color.</summary>
  264. public const ColorName16 Yellow = ColorName16.Yellow;
  265. /// <summary>The gray color.</summary>
  266. public const ColorName16 Gray = ColorName16.Gray;
  267. /// <summary>The dark gray color.</summary>
  268. public const ColorName16 DarkGray = ColorName16.DarkGray;
  269. /// <summary>The bright bBlue color.</summary>
  270. public const ColorName16 BrightBlue = ColorName16.BrightBlue;
  271. /// <summary>The bright green color.</summary>
  272. public const ColorName16 BrightGreen = ColorName16.BrightGreen;
  273. /// <summary>The bright cyan color.</summary>
  274. public const ColorName16 BrightCyan = ColorName16.BrightCyan;
  275. /// <summary>The bright red color.</summary>
  276. public const ColorName16 BrightRed = ColorName16.BrightRed;
  277. /// <summary>The bright magenta color.</summary>
  278. public const ColorName16 BrightMagenta = ColorName16.BrightMagenta;
  279. /// <summary>The bright yellow color.</summary>
  280. public const ColorName16 BrightYellow = ColorName16.BrightYellow;
  281. /// <summary>The White color.</summary>
  282. public const ColorName16 White = ColorName16.White;
  283. #endregion
  284. }