Color.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. using System.Collections.Frozen;
  2. using System.Globalization;
  3. using System.Numerics;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. using System.Text.Json.Serialization;
  7. using ColorHelper;
  8. using ColorConverter = ColorHelper.ColorConverter;
  9. namespace Terminal.Gui.Drawing;
  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="ColorName16"/>
  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 ColorName16 colorName) { this = ColorExtensions.ColorName16ToColorMap! [colorName]; }
  99. /// <summary>Initializes a new instance of the <see cref="Color"/> color from a value in the <see cref="StandardColor"/> enum.</summary>
  100. /// <param name="colorName">The 16-color value.</param>
  101. public Color (in StandardColor colorName) : this (StandardColors.GetArgb (colorName)) { }
  102. /// <summary>
  103. /// Initializes a new instance of the <see cref="Color"/> color from string. See
  104. /// <see cref="TryParse(string, out Color?)"/> for details.
  105. /// </summary>
  106. /// <param name="colorString"></param>
  107. /// <exception cref="ArgumentNullException">If <paramref name="colorString"/> is <see langword="null"/>.</exception>
  108. /// <exception cref="ArgumentException">
  109. /// If <paramref name="colorString"/> is an empty string or consists of only whitespace
  110. /// characters.
  111. /// </exception>
  112. /// <exception cref="ColorParseException">If thrown by <see cref="Parse(string?,System.IFormatProvider?)"/></exception>
  113. public Color (string colorString)
  114. {
  115. ArgumentException.ThrowIfNullOrWhiteSpace (colorString, nameof (colorString));
  116. this = Parse (colorString, CultureInfo.InvariantCulture);
  117. }
  118. /// <summary>Initializes a new instance of the <see cref="Color"/> with all channels set to 0.</summary>
  119. public Color () { Argb = 0u; }
  120. // TODO: ColorName and AnsiColorCode are only needed when a driver is in Force16Color mode and we
  121. // TODO: should be able to remove these from any non-Driver-specific usages.
  122. /// <summary>Gets or sets the 3-byte/6-character hexadecimal value for each of the legacy 16-color values.</summary>
  123. [ConfigurationProperty (Scope = typeof (SettingsScope), OmitClassName = true)]
  124. public static Dictionary<ColorName16, string> Colors16
  125. {
  126. get =>
  127. // Transform _colorToNameMap into a Dictionary<ColorNames,string>
  128. ColorExtensions.ColorToName16Map!.ToDictionary (static kvp => kvp.Value, static kvp => kvp.Key.ToString ("g"));
  129. set
  130. {
  131. // Transform Dictionary<ColorNames,string> into _colorToNameMap
  132. ColorExtensions.ColorToName16Map = value.ToFrozenDictionary (GetColorToNameMapKey, GetColorToNameMapValue);
  133. return;
  134. static Color GetColorToNameMapKey (KeyValuePair<ColorName16, string> kvp) { return new (kvp.Value); }
  135. static ColorName16 GetColorToNameMapValue (KeyValuePair<ColorName16, string> kvp)
  136. {
  137. return Enum.TryParse (kvp.Key.ToString (), true, out ColorName16 colorName)
  138. ? colorName
  139. : throw new ArgumentException ($"Invalid color name: {kvp.Key}");
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Gets the <see cref="Color"/> using a legacy 16-color <see cref="ColorName16"/> value. <see langword="get"/> will
  145. /// return the closest 16 color match to the true color when no exact value is found.
  146. /// </summary>
  147. /// <remarks>
  148. /// Get returns the <see cref="GetClosestNamedColor16(Color)"/> of the closest 24-bit color value. Set sets the RGB
  149. /// value using a hard-coded map.
  150. /// </remarks>
  151. public AnsiColorCode GetAnsiColorCode () { return ColorExtensions.ColorName16ToAnsiColorMap [GetClosestNamedColor16 ()]; }
  152. /// <summary>
  153. /// Gets the <see cref="Color"/> using a legacy 16-color <see cref="ColorName16"/> value. <see langword="get"/>
  154. /// will return the closest 16 color match to the true color when no exact value is found.
  155. /// </summary>
  156. /// <remarks>
  157. /// Get returns the <see cref="GetClosestNamedColor16(Color)"/> of the closest 24-bit color value. Set
  158. /// sets the RGB
  159. /// value using a hard-coded map.
  160. /// </remarks>
  161. public ColorName16 GetClosestNamedColor16 () { return GetClosestNamedColor16 (this); }
  162. /// <summary>
  163. /// Determines if the closest named <see cref="Color"/> to <see langword="this"/> is the provided
  164. /// <paramref name="namedColor"/>.
  165. /// </summary>
  166. /// <param name="namedColor">
  167. /// The <see cref="GetClosestNamedColor16(Color)"/> to check if this <see cref="Color"/> is closer
  168. /// to than any other configured named color.
  169. /// </param>
  170. /// <returns>
  171. /// <see langword="true"/> if the closest named color is the provided value. <br/> <see langword="false"/> if any
  172. /// other named color is closer to this <see cref="Color"/> than <paramref name="namedColor"/>.
  173. /// </returns>
  174. /// <remarks>
  175. /// If <see langword="this"/> is equidistant from two named colors, the result of this method is not guaranteed to
  176. /// be determinate.
  177. /// </remarks>
  178. [Pure]
  179. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  180. public bool IsClosestToNamedColor16 (in ColorName16 namedColor) { return GetClosestNamedColor16 () == namedColor; }
  181. /// <summary>
  182. /// Determines if the closest named <see cref="Color"/> to <paramref name="color"/>/> is the provided
  183. /// <paramref name="namedColor"/>.
  184. /// </summary>
  185. /// <param name="color">
  186. /// The color to test against the <see cref="GetClosestNamedColor16(Color)"/> value in
  187. /// <paramref name="namedColor"/>.
  188. /// </param>
  189. /// <param name="namedColor">
  190. /// The <see cref="GetClosestNamedColor16(Color)"/> to check if this <see cref="Color"/> is closer
  191. /// to than any other configured named color.
  192. /// </param>
  193. /// <returns>
  194. /// <see langword="true"/> if the closest named color to <paramref name="color"/> is the provided value. <br/>
  195. /// <see langword="false"/> if any other named color is closer to <paramref name="color"/> than
  196. /// <paramref name="namedColor"/>.
  197. /// </returns>
  198. /// <remarks>
  199. /// If <paramref name="color"/> is equidistant from two named colors, the result of this method is not guaranteed
  200. /// to be determinate.
  201. /// </remarks>
  202. [Pure]
  203. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  204. public static bool IsColorClosestToNamedColor16 (in Color color, in ColorName16 namedColor) { return color.IsClosestToNamedColor16 (in namedColor); }
  205. /// <summary>Gets the "closest" named color to this <see cref="Color"/> value.</summary>
  206. /// <param name="inputColor"></param>
  207. /// <remarks>
  208. /// Distance is defined here as the Euclidean distance between each color interpreted as a <see cref="Vector3"/>.
  209. /// </remarks>
  210. /// <returns></returns>
  211. [SkipLocalsInit]
  212. internal static ColorName16 GetClosestNamedColor16 (Color inputColor)
  213. {
  214. return ColorExtensions.ColorToName16Map!.MinBy (pair => CalculateColorDistance (inputColor, pair.Key)).Value;
  215. }
  216. /// <summary>Converts the given color value to exact named color represented by <see cref="ColorName16"/>.</summary>
  217. /// <param name="inputColor"></param>
  218. /// <param name="colorName16">Successfully converted named color.</param>
  219. /// <returns>True if conversion succeeded; otherwise false.</returns>
  220. internal static bool TryGetExactNamedColor16 (Color inputColor, out ColorName16 colorName16)
  221. {
  222. return ColorExtensions.ColorToName16Map!.TryGetValue (inputColor, out colorName16);
  223. }
  224. [SkipLocalsInit]
  225. private static float CalculateColorDistance (in Vector4 color1, in Vector4 color2) { return Vector4.Distance (color1, color2); }
  226. /// <summary>
  227. /// Returns a color with the same hue and saturation as this color, but with a significantly different lightness,
  228. /// making it suitable for use as a highlight or contrast color in UI elements.
  229. /// </summary>
  230. /// <remarks>
  231. /// <para>
  232. /// This method brightens the color if it is dark, or darkens it if it is light, ensuring the result is visually
  233. /// distinct
  234. /// from the original. The algorithm works in HSL color space and adjusts the lightness channel:
  235. /// <list type="bullet">
  236. /// <item>
  237. /// <description>If the color is dark (lightness &lt; 0.5), the lightness is increased (brightened).</description>
  238. /// </item>
  239. /// <item>
  240. /// <description>If the color is light (lightness &gt;= 0.5), the lightness is decreased (darkened).</description>
  241. /// </item>
  242. /// <item>
  243. /// <description>
  244. /// If the adjustment resulted in a color too close to the original, a larger adjustment is
  245. /// made.
  246. /// </description>
  247. /// </item>
  248. /// </list>
  249. /// This ensures the returned color is always visually distinct and suitable for highlighting or selection states.
  250. /// </para>
  251. /// <para>
  252. /// The returned color will always have the same hue and saturation as the original, but a different lightness.
  253. /// </para>
  254. /// </remarks>
  255. /// <param name="brightenAmount">The percent amount to brighten the color by. The default is <c>20%</c>.</param>
  256. /// <returns>
  257. /// A <see cref="Color"/> instance with the same hue and saturation as this color, but with a contrasting lightness.
  258. /// </returns>
  259. /// <example>
  260. /// <code>
  261. /// var baseColor = new Color(100, 100, 100);
  262. /// var highlight = baseColor.GetHighlightColor();
  263. /// // highlight will be a lighter or darker version of baseColor, depending on its original lightness.
  264. /// </code>
  265. /// </example>
  266. public Color GetBrighterColor (double brightenAmount = 0.2)
  267. {
  268. HSL? hsl = ColorConverter.RgbToHsl (new (R, G, B));
  269. double lNorm = hsl.L / 255.0;
  270. double newL;
  271. if (lNorm < 0.5)
  272. {
  273. newL = Math.Min (1.0, lNorm + brightenAmount);
  274. }
  275. else
  276. {
  277. newL = Math.Max (0.0, lNorm - brightenAmount);
  278. }
  279. if (Math.Abs (newL - lNorm) < 0.1)
  280. {
  281. newL = lNorm < 0.5 ? Math.Min (1.0, lNorm + 2 * brightenAmount) : Math.Max (0.0, lNorm - 2 * brightenAmount);
  282. }
  283. var newHsl = new HSL (hsl.H, hsl.S, (byte)(newL * 255));
  284. RGB? rgb = ColorConverter.HslToRgb (newHsl);
  285. return new (rgb.R, rgb.G, rgb.B);
  286. }
  287. /// <summary>
  288. /// Returns a color with the same hue and saturation as this color, but with a significantly lower lightness,
  289. /// making it suitable for use as a shadow or background contrast color in UI elements.
  290. /// </summary>
  291. /// <remarks>
  292. /// <para>
  293. /// This method darkens the color by reducing its lightness in HSL color space:
  294. /// <list type="bullet">
  295. /// <item>
  296. /// <description>If the color is already very dark, returns <see cref="ColorName16.DarkGray"/>.</description>
  297. /// </item>
  298. /// <item>
  299. /// <description>Otherwise, reduces the lightness by a fixed amount (default 30%).</description>
  300. /// </item>
  301. /// <item>
  302. /// <description>
  303. /// If the adjustment resulted in a color too close to the original, a larger adjustment is
  304. /// made.
  305. /// </description>
  306. /// </item>
  307. /// </list>
  308. /// This ensures the returned color is always visually distinct and suitable for shadowing or de-emphasis.
  309. /// </para>
  310. /// </remarks>
  311. /// <param name="dimAmount">The percent amount to dim the color by. The default is <c>20%</c>.</param>
  312. /// <returns>
  313. /// A <see cref="Color"/> instance with the same hue and saturation as this color, but with a much lower lightness.
  314. /// </returns>
  315. public Color GetDimColor (double dimAmount = 0.2)
  316. {
  317. HSL hsl = ColorConverter.RgbToHsl (new (R, G, B));
  318. double lNorm = hsl.L / 255.0;
  319. double newL = Math.Max (0.0, lNorm - dimAmount);
  320. // If the color is already very dark, return a standard dark gray for visibility
  321. if (lNorm <= 0.1)
  322. {
  323. return new (ColorName16.DarkGray);
  324. }
  325. // If the new lightness is too close to the original, force a bigger change
  326. if (Math.Abs (newL - lNorm) < 0.1)
  327. {
  328. newL = Math.Max (0.0, lNorm - 2 * dimAmount);
  329. }
  330. var newHsl = new HSL (hsl.H, hsl.S, (byte)(newL * 255));
  331. RGB rgb = ColorConverter.HslToRgb (newHsl);
  332. return new (rgb.R, rgb.G, rgb.B);
  333. }
  334. #region Legacy Color Names
  335. // ReSharper disable InconsistentNaming
  336. /// <summary>The black color.</summary>
  337. public const ColorName16 Black = ColorName16.Black;
  338. /// <summary>The blue color.</summary>
  339. public const ColorName16 Blue = ColorName16.Blue;
  340. /// <summary>The green color.</summary>
  341. public const ColorName16 Green = ColorName16.Green;
  342. /// <summary>The cyan color.</summary>
  343. public const ColorName16 Cyan = ColorName16.Cyan;
  344. /// <summary>The red color.</summary>
  345. public const ColorName16 Red = ColorName16.Red;
  346. /// <summary>The magenta color.</summary>
  347. public const ColorName16 Magenta = ColorName16.Magenta;
  348. /// <summary>The yellow color.</summary>
  349. public const ColorName16 Yellow = ColorName16.Yellow;
  350. /// <summary>The gray color.</summary>
  351. public const ColorName16 Gray = ColorName16.Gray;
  352. /// <summary>The dark gray color.</summary>
  353. public const ColorName16 DarkGray = ColorName16.DarkGray;
  354. /// <summary>The bright bBlue color.</summary>
  355. public const ColorName16 BrightBlue = ColorName16.BrightBlue;
  356. /// <summary>The bright green color.</summary>
  357. public const ColorName16 BrightGreen = ColorName16.BrightGreen;
  358. /// <summary>The bright cyan color.</summary>
  359. public const ColorName16 BrightCyan = ColorName16.BrightCyan;
  360. /// <summary>The bright red color.</summary>
  361. public const ColorName16 BrightRed = ColorName16.BrightRed;
  362. /// <summary>The bright magenta color.</summary>
  363. public const ColorName16 BrightMagenta = ColorName16.BrightMagenta;
  364. /// <summary>The bright yellow color.</summary>
  365. public const ColorName16 BrightYellow = ColorName16.BrightYellow;
  366. /// <summary>The White color.</summary>
  367. public const ColorName16 White = ColorName16.White;
  368. #endregion
  369. }