Color.cs 13 KB

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