global using Attribute = Terminal.Gui.Attribute; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using System.Text.RegularExpressions; namespace Terminal.Gui { /// /// Defines the 16 legacy color names and values that can be used to set the foreground and background colors in Terminal.Gui apps. Used with . /// /// /// /// public enum ColorNames { /// /// The black color. /// Black, /// /// The blue color. /// Blue, /// /// The green color. /// Green, /// /// The cyan color. /// Cyan, /// /// The red color. /// Red, /// /// The magenta color. /// Magenta, /// /// The brown color. /// Brown, /// /// The gray color. /// Gray, /// /// The dark gray color. /// DarkGray, /// /// The bright bBlue color. /// BrightBlue, /// /// The bright green color. /// BrightGreen, /// /// The bright cyan color. /// BrightCyan, /// /// The bright red color. /// BrightRed, /// /// The bright magenta color. /// BrightMagenta, /// /// The bright yellow color. /// BrightYellow, /// /// The White color. /// White } /// /// Represents a color in the console. This is used with . /// [JsonConverter (typeof (ColorJsonConverter))] public class Color : IEquatable { /// /// Initializes a new instance of the class. /// /// /// /// public Color (int red, int green, int blue) { A = 0xFF; R = red; G = green; B = blue; } /// /// Initializes a new instance of the class. /// /// /// /// /// public Color (int alpha, int red, int green, int blue) { A = alpha; R = red; G = green; B = blue; } /// /// Initializes a new instance of the class with an encoded 24-bit color value. /// /// The encoded 24-bit color value. public Color (int argb) { Value = argb; } /// /// Initializes a new instance of the color from a legacy 16-color value. /// /// The 16-color value. public Color (ColorNames colorName) { var c = Color.FromColorName (colorName); A = c.A; R = c.R; G = c.G; B = c.B; } /// /// Initializes a new instance of the . /// public Color () { A = 0xFF; R = 0; G = 0; B = 0; } /// /// Red color component. /// public int R { get; set; } /// /// Green color component. /// public int G { get; set; } /// /// Blue color component. /// public int B { get; set; } /// /// Alpha color component. /// /// /// Not currently supported; here for completeness. /// public int A { get; set; } /// /// Gets or sets the color value encoded using the following code: /// /// (<see cref="A"/> << 24) | (<see cref="R"/> << 16) | (<see cref="G"/> << 8) | <see cref="B"/> /// /// public int Value { get => (A << 24) | (R << 16) | (G << 8) | B; set { A = (byte)((value >> 24) & 0xFF); R = (byte)((value >> 16) & 0xFF); G = (byte)((value >> 8) & 0xFF); B = (byte)(value & 0xFF); } } // TODO: Make this map configurable via ConfigurationManager // TODO: This does not need to be a Dictionary, but can be an 16 element array. /// /// Maps legacy 16-color values to the corresponding 24-bit RGB value. /// internal static readonly ImmutableDictionary _colorNames = new Dictionary () { // using "Windows 10 Console/PowerShell 6" here: https://i.stack.imgur.com/9UVnC.png { new Color (12, 12, 12),ColorNames.Black }, { new Color (0, 55, 218),ColorNames.Blue }, { new Color (19, 161, 14),ColorNames.Green}, { new Color (58, 150, 221),ColorNames.Cyan}, { new Color (197, 15, 31),ColorNames.Red}, { new Color (136, 23, 152),ColorNames.Magenta}, { new Color (128, 64, 32),ColorNames.Brown}, { new Color (204, 204, 204),ColorNames.Gray}, { new Color (118, 118, 118),ColorNames.DarkGray}, { new Color (59, 120, 255),ColorNames.BrightBlue}, { new Color (22, 198, 12),ColorNames.BrightGreen}, { new Color (97, 214, 214),ColorNames.BrightCyan}, { new Color (231, 72, 86),ColorNames.BrightRed}, { new Color (180, 0, 158),ColorNames.BrightMagenta }, { new Color (249, 241, 165),ColorNames.BrightYellow}, { new Color (242, 242, 242),ColorNames.White}, }.ToImmutableDictionary (); /// /// Converts a legacy to a 24-bit . /// /// The to convert. /// private static Color FromColorName (ColorNames consoleColor) => _colorNames.FirstOrDefault (x => x.Value == consoleColor).Key; // Iterates through the entries in the _colorNames dictionary, calculates the // Euclidean distance between the input color and each dictionary color in RGB space, // and keeps track of the closest entry found so far. The function returns a KeyValuePair // representing the closest color entry and its associated color name. internal static ColorNames FindClosestColor (Color inputColor) { ColorNames closestColor = ColorNames.Black; // Default to Black double closestDistance = double.MaxValue; foreach (var colorEntry in _colorNames) { var distance = CalculateColorDistance (inputColor, colorEntry.Key); if (distance < closestDistance) { closestDistance = distance; closestColor = colorEntry.Value; } } return closestColor; } private static double CalculateColorDistance (Color color1, Color color2) { // Calculate the Euclidean distance between two colors var deltaR = (double)color1.R - (double)color2.R; var deltaG = (double)color1.G - (double)color2.G; var deltaB = (double)color1.B - (double)color2.B; return Math.Sqrt (deltaR * deltaR + deltaG * deltaG + deltaB * deltaB); } /// /// Gets or sets the using a legacy 16-color value. /// /// /// Get returns the closest 24-bit color value. Set sets the RGB value using a hard-coded map. /// public ColorNames ColorName { get => FindClosestColor (this.Value); set { var c = FromColorName (value); A = c.A; R = c.R; G = c.G; B = c.B; } } #region Legacy Color Names /// /// /// The black color. /// public const ColorNames Black = ColorNames.Black; /// /// The blue color. /// public const ColorNames Blue = ColorNames.Blue; /// /// The green color. /// public const ColorNames Green = ColorNames.Green; /// /// The cyan color. /// public const ColorNames Cyan = ColorNames.Cyan; /// /// The red color. /// public const ColorNames Red = ColorNames.Red; /// /// The magenta color. /// public const ColorNames Magenta = ColorNames.Magenta; /// /// The brown color. /// public const ColorNames Brown = ColorNames.Brown; /// /// The gray color. /// public const ColorNames Gray = ColorNames.Gray; /// /// The dark gray color. /// public const ColorNames DarkGray = ColorNames.DarkGray; /// /// The bright bBlue color. /// public const ColorNames BrightBlue = ColorNames.BrightBlue; /// /// The bright green color. /// public const ColorNames BrightGreen = ColorNames.BrightGreen; /// /// The bright cyan color. /// public const ColorNames BrightCyan = ColorNames.BrightCyan; /// /// The bright red color. /// public const ColorNames BrightRed = ColorNames.BrightRed; /// /// The bright magenta color. /// public const ColorNames BrightMagenta = ColorNames.BrightMagenta; /// /// The bright yellow color. /// public const ColorNames BrightYellow = ColorNames.BrightYellow; /// /// The White color. /// public const ColorNames White = ColorNames.White; #endregion /// /// Converts the provided text to a new instance. /// /// The text to analyze. /// The parsed value. /// A boolean value indicating whether it was successful. public static bool TryParse (string text, [NotNullWhen (true)] out Color color) { // empty color if ((text == null) || (text.Length == 0)) { color = null; return false; } // #RRGGBB, #RGB if ((text [0] == '#') && text.Length is 7 or 4) { if (text.Length == 7) { var r = Convert.ToInt32 (text.Substring (1, 2), 16); var g = Convert.ToInt32 (text.Substring (3, 2), 16); var b = Convert.ToInt32 (text.Substring (5, 2), 16); color = new Color (r, g, b); } else { var rText = char.ToString (text [1]); var gText = char.ToString (text [2]); var bText = char.ToString (text [3]); var r = Convert.ToInt32 (rText + rText, 16); var g = Convert.ToInt32 (gText + gText, 16); var b = Convert.ToInt32 (bText + bText, 16); color = new Color (r, g, b); } return true; } // #AARRGGBB, #ARGB if ((text [0] == '#') && text.Length is 8 or 5) { if (text.Length == 7) { var a = Convert.ToInt32 (text.Substring (1, 2), 16); var r = Convert.ToInt32 (text.Substring (3, 2), 16); var g = Convert.ToInt32 (text.Substring (5, 2), 16); var b = Convert.ToInt32 (text.Substring (7, 2), 16); color = new Color (a, r, g, b); } else { var aText = char.ToString (text [1]); var rText = char.ToString (text [2]); var gText = char.ToString (text [3]); var bText = char.ToString (text [4]); var a = Convert.ToInt32 (aText + aText, 16); var r = Convert.ToInt32 (rText + rText, 16); var g = Convert.ToInt32 (gText + gText, 16); var b = Convert.ToInt32 (bText + bText, 16); color = new Color (a, r, g, b); } return true; } // rgb(XX,YY,ZZ) var match = Regex.Match (text, @"rgb\((\d+),(\d+),(\d+)\)"); if (match.Success) { var r = int.Parse (match.Groups [1].Value); var g = int.Parse (match.Groups [2].Value); var b = int.Parse (match.Groups [3].Value); color = new Color (r, g, b); return true; } // rgb(AA,XX,YY,ZZ) match = Regex.Match (text, @"rgb\((\d+),(\d+),(\d+),(\d+)\)"); if (match.Success) { var a = int.Parse (match.Groups [1].Value); var r = int.Parse (match.Groups [2].Value); var g = int.Parse (match.Groups [3].Value); var b = int.Parse (match.Groups [4].Value); color = new Color (a, r, g, b); return true; } color = null; return false; } #region Operators /// /// Cast from int. /// /// public static implicit operator Color (int argb) { return new Color (argb); } /// /// Cast to int. /// /// public static explicit operator int (Color color) { return color.Value; } /// /// Cast from . /// /// public static explicit operator Color (ColorNames colorName) { return new Color (colorName); } /// /// Cast to . /// /// public static explicit operator ColorNames (Color color) { return color.ColorName; } /// /// Equality operator for two objects.. /// /// /// /// public static bool operator == (Color left, Color right) { return left.Equals (right); } /// /// Inequality operator for two objects. /// /// /// /// public static bool operator != (Color left, Color right) { return !left.Equals (right); } /// /// Equality operator for and objects. /// /// /// /// public static bool operator == (ColorNames left, Color right) { return left == right.ColorName; } /// /// Inequality operator for and objects. /// /// /// /// public static bool operator != (ColorNames left, Color right) { return left != right.ColorName; } /// /// Equality operator for and objects. /// /// /// /// public static bool operator == (Color left, ColorNames right) { return left.ColorName == right; } /// /// Inequality operator for and objects. /// /// /// /// public static bool operator != (Color left, ColorNames right) { return left.ColorName != right; } /// public override bool Equals (object obj) { return obj is Color other && Equals (other); } /// public bool Equals (Color other) { return A == other.A && R == other.R && G == other.G && B == other.B; } /// public override int GetHashCode () { return HashCode.Combine (A, R, G, B); } #endregion /// /// Converts the color to a string representation. /// /// /// If the color is a named color, the name is returned. Otherwise, the color is returned as a hex string. /// /// public override string ToString () { // If Values has an exact match with a named color (in _colorNames), use that. if (_colorNames.TryGetValue (this, out ColorNames colorName)) { return Enum.GetName (typeof (ColorNames), colorName); } // Otherwise return as an RGB hex value. return $"#{R:X2}{G:X2}{B:X2}"; } } // TODO: Get rid of all the Initialized crap - it's not needed once Curses Driver supports TrueColor /// /// Attributes represent how text is styled when displayed in the terminal. /// /// /// provides a platform independent representation of colors (and someday other forms of text styling). /// They encode both the foreground and the background color and are used in the /// class to define color schemes that can be used in an application. /// [JsonConverter (typeof (AttributeJsonConverter))] public struct Attribute : IEquatable { /// /// Default empty attribute. /// public static readonly Attribute Default = new Attribute (Color.White, Color.Black); /// /// The -specific color value. If is /// the value of this property is invalid (typically because the Attribute was created before a driver was loaded) /// and the attribute should be re-made (see ) before it is used. /// [JsonIgnore (Condition = JsonIgnoreCondition.Always)] internal int Value { get; } /// /// The foreground color. /// [JsonConverter (typeof (ColorJsonConverter))] public Color Foreground { get; private init; } /// /// The background color. /// [JsonConverter (typeof (ColorJsonConverter))] public Color Background { get; private init; } /// /// Initializes a new instance with default values. /// public Attribute () { var d = Default; Value = -1; Foreground = d.Foreground; Background = d.Background; } /// /// Initializes a new instance with platform specific color value. /// /// Value. internal Attribute (int platformColor) : this (platformColor, Default.Foreground, Default.Background) { } /// /// Initializes a new instance of the struct. /// /// platform-dependent color value. /// Foreground /// Background internal Attribute (int platformColor, Color foreground, Color background) { Foreground = foreground; Background = background; Value = platformColor; Initialized = true; } /// /// Initializes a new instance of the struct. /// /// platform-dependent color value. /// Foreground /// Background internal Attribute (int platformColor, ColorNames foreground, ColorNames background) : this (platformColor, (Color)foreground, (Color)background) { } /// /// Initializes a new instance of the struct. /// /// Foreground /// Background public Attribute (Color foreground, Color background) { Foreground = foreground; Background = background; if (Application.Driver == null) { // Create the attribute, but show it's not been initialized Initialized = false; Value = -1; return; } var make = Application.Driver.MakeAttribute (foreground, background); Initialized = make.Initialized; Value = make.Value; } /// /// Initializes a new instance with a value. Both and /// will be set to the specified color. /// /// Value. internal Attribute (ColorNames colorName) : this (colorName, colorName) { } /// /// Initializes a new instance of the struct. /// /// Foreground /// Background public Attribute (ColorNames foregroundName, ColorNames backgroundName) : this (new Color (foregroundName), new Color (backgroundName)) { } /// /// Initializes a new instance of the struct. /// /// Foreground /// Background public Attribute (ColorNames foregroundName, Color background) : this (new Color (foregroundName), background) { } /// /// Initializes a new instance of the struct. /// /// Foreground /// Background public Attribute (Color foreground, ColorNames backgroundName) : this (foreground, new Color (backgroundName)) { } /// /// Initializes a new instance of the struct /// with the same colors for the foreground and background. /// /// The color. public Attribute (Color color) : this (color, color) { } /// /// Compares two attributes for equality. /// /// /// /// public static bool operator == (Attribute left, Attribute right) => left.Equals (right); /// /// Compares two attributes for inequality. /// /// /// /// public static bool operator != (Attribute left, Attribute right) => !(left == right); /// public override bool Equals (object obj) { return obj is Attribute other && Equals (other); } /// public bool Equals (Attribute other) { return Value == other.Value && Foreground == other.Foreground && Background == other.Background; } /// public override int GetHashCode () => HashCode.Combine (Value, Foreground, Background); /// /// If the attribute has been initialized by a and /// thus has that is valid for that driver. If the /// and colors may have been set '-1' but /// the attribute has not been mapped to a specific color value. /// /// /// Attributes that have not been initialized must eventually be initialized before being passed to a driver. /// [JsonIgnore] public bool Initialized { get; internal set; } /// /// Returns if the Attribute is valid (both foreground and background have valid color values). /// /// [JsonIgnore] public bool HasValidColors => (int)Foreground.ColorName > -1 && (int)Background.ColorName > -1; /// public override string ToString () { // Note, Unit tests are dependent on this format return $"{Foreground},{Background}"; } } /// /// Defines the color s for common visible elements in a . /// Containers such as and use to determine /// the colors used by sub-views. /// /// /// See also: . /// [JsonConverter (typeof (ColorSchemeJsonConverter))] public class ColorScheme : IEquatable { Attribute _normal = Attribute.Default; Attribute _focus = Attribute.Default; Attribute _hotNormal = Attribute.Default; Attribute _hotFocus = Attribute.Default; Attribute _disabled = Attribute.Default; /// /// Used by and to track which ColorScheme /// is being accessed. /// internal string schemeBeingSet = ""; /// /// Creates a new instance. /// public ColorScheme () : this (Attribute.Default) { } /// /// Creates a new instance, initialized with the values from . /// /// The scheme to initialize the new instance with. public ColorScheme (ColorScheme scheme) : base () { if (scheme != null) { _normal = scheme.Normal; _focus = scheme.Focus; _hotNormal = scheme.HotNormal; _disabled = scheme.Disabled; _hotFocus = scheme.HotFocus; } } /// /// Creates a new instance, initialized with the values from . /// /// The attribute to initialize the new instance with. public ColorScheme (Attribute attribute) { _normal = attribute; _focus = attribute; _hotNormal = attribute; _disabled = attribute; _hotFocus = attribute; } /// /// The foreground and background color for text when the view is not focused, hot, or disabled. /// public Attribute Normal { get { return _normal; } set { if (!value.HasValidColors) { return; } _normal = value; } } /// /// The foreground and background color for text when the view has the focus. /// public Attribute Focus { get { return _focus; } set { if (!value.HasValidColors) { return; } _focus = value; } } /// /// The foreground and background color for text when the view is highlighted (hot). /// public Attribute HotNormal { get { return _hotNormal; } set { if (!value.HasValidColors) { return; } _hotNormal = value; } } /// /// The foreground and background color for text when the view is highlighted (hot) and has focus. /// public Attribute HotFocus { get { return _hotFocus; } set { if (!value.HasValidColors) { return; } _hotFocus = value; } } /// /// The default foreground and background color for text, when the view is disabled. /// public Attribute Disabled { get { return _disabled; } set { if (!value.HasValidColors) { return; } _disabled = value; } } /// /// Compares two objects for equality. /// /// /// true if the two objects are equal public override bool Equals (object obj) { return Equals (obj as ColorScheme); } /// /// Compares two objects for equality. /// /// /// true if the two objects are equal public bool Equals (ColorScheme other) { return other != null && EqualityComparer.Default.Equals (_normal, other._normal) && EqualityComparer.Default.Equals (_focus, other._focus) && EqualityComparer.Default.Equals (_hotNormal, other._hotNormal) && EqualityComparer.Default.Equals (_hotFocus, other._hotFocus) && EqualityComparer.Default.Equals (_disabled, other._disabled); } /// /// Returns a hashcode for this instance. /// /// hashcode for this instance public override int GetHashCode () { int hashCode = -1242460230; hashCode = hashCode * -1521134295 + _normal.GetHashCode (); hashCode = hashCode * -1521134295 + _focus.GetHashCode (); hashCode = hashCode * -1521134295 + _hotNormal.GetHashCode (); hashCode = hashCode * -1521134295 + _hotFocus.GetHashCode (); hashCode = hashCode * -1521134295 + _disabled.GetHashCode (); return hashCode; } /// /// Compares two objects for equality. /// /// /// /// true if the two objects are equivalent public static bool operator == (ColorScheme left, ColorScheme right) { return EqualityComparer.Default.Equals (left, right); } /// /// Compares two objects for inequality. /// /// /// /// true if the two objects are not equivalent public static bool operator != (ColorScheme left, ColorScheme right) { return !(left == right); } internal void Initialize () { // If the new scheme was created before a driver was loaded, we need to re-make // the attributes if (!_normal.Initialized) { _normal = new Attribute (_normal.Foreground, _normal.Background); } if (!_focus.Initialized) { _focus = new Attribute (_focus.Foreground, _focus.Background); } if (!_hotNormal.Initialized) { _hotNormal = new Attribute (_hotNormal.Foreground, _hotNormal.Background); } if (!_hotFocus.Initialized) { _hotFocus = new Attribute (_hotFocus.Foreground, _hotFocus.Background); } if (!_disabled.Initialized) { _disabled = new Attribute (_disabled.Foreground, _disabled.Background); } } } /// /// The default s for the application. /// /// /// This property can be set in a Theme to change the default for the application. /// public static class Colors { private class SchemeNameComparerIgnoreCase : IEqualityComparer { public bool Equals (string x, string y) { if (x != null && y != null) { return string.Equals (x, y, StringComparison.InvariantCultureIgnoreCase); } return false; } public int GetHashCode (string obj) { return obj.ToLowerInvariant ().GetHashCode (); } } static Colors () { ColorSchemes = Create (); } /// /// Creates a new dictionary of new objects. /// public static Dictionary Create () { // Use reflection to dynamically create the default set of ColorSchemes from the list defined // by the class. return typeof (Colors).GetProperties () .Where (p => p.PropertyType == typeof (ColorScheme)) .Select (p => new KeyValuePair (p.Name, new ColorScheme ())) .ToDictionary (t => t.Key, t => t.Value, comparer: new SchemeNameComparerIgnoreCase ()); } /// /// The application Toplevel color scheme, for the default Toplevel views. /// /// /// /// This API will be deprecated in the future. Use instead (e.g. edit.ColorScheme = Colors.ColorSchemes["TopLevel"]; /// /// public static ColorScheme TopLevel { get => GetColorScheme (); set => SetColorScheme (value); } /// /// The base color scheme, for the default Toplevel views. /// /// /// /// This API will be deprecated in the future. Use instead (e.g. edit.ColorScheme = Colors.ColorSchemes["Base"]; /// /// public static ColorScheme Base { get => GetColorScheme (); set => SetColorScheme (value); } /// /// The dialog color scheme, for standard popup dialog boxes /// /// /// /// This API will be deprecated in the future. Use instead (e.g. edit.ColorScheme = Colors.ColorSchemes["Dialog"]; /// /// public static ColorScheme Dialog { get => GetColorScheme (); set => SetColorScheme (value); } /// /// The menu bar color /// /// /// /// This API will be deprecated in the future. Use instead (e.g. edit.ColorScheme = Colors.ColorSchemes["Menu"]; /// /// public static ColorScheme Menu { get => GetColorScheme (); set => SetColorScheme (value); } /// /// The color scheme for showing errors. /// /// /// /// This API will be deprecated in the future. Use instead (e.g. edit.ColorScheme = Colors.ColorSchemes["Error"]; /// /// public static ColorScheme Error { get => GetColorScheme (); set => SetColorScheme (value); } static ColorScheme GetColorScheme ([CallerMemberName] string schemeBeingSet = null) { return ColorSchemes [schemeBeingSet]; } static void SetColorScheme (ColorScheme colorScheme, [CallerMemberName] string schemeBeingSet = null) { ColorSchemes [schemeBeingSet] = colorScheme; colorScheme.schemeBeingSet = schemeBeingSet; } /// /// Provides the defined s. /// [SerializableConfigurationProperty (Scope = typeof (ThemeScope), OmitClassName = true)] [JsonConverter (typeof (DictionaryJsonConverter))] public static Dictionary ColorSchemes { get; private set; } } }