ParseColor parses a string in both hex or rgb or from XResources or env variable and converts to both rgb and hex value
(raw string)
| 74 | // or from XResources or env variable |
| 75 | // and converts to both rgb and hex value |
| 76 | func ParseColor(raw string) Color { |
| 77 | var red, green, blue int64 |
| 78 | |
| 79 | if strings.HasPrefix(raw, "${") { |
| 80 | endIndex := len(raw) - 1 |
| 81 | raw = raw[2:endIndex] |
| 82 | |
| 83 | // From XResources database |
| 84 | if strings.HasPrefix(raw, "xrdb:") { |
| 85 | raw = fromXResources(raw) |
| 86 | |
| 87 | // From environment variable |
| 88 | } else if env := os.Getenv(raw); len(env) > 0 { |
| 89 | raw = env |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // rrr,bbb,ggg |
| 94 | if strings.Contains(raw, ",") { |
| 95 | list := strings.SplitN(raw, ",", 3) |
| 96 | list = append(list, "255", "255") |
| 97 | |
| 98 | red = stringToInt(list[0], 10) |
| 99 | green = stringToInt(list[1], 10) |
| 100 | blue = stringToInt(list[2], 10) |
| 101 | |
| 102 | } else { |
| 103 | re := regexp.MustCompile("[a-fA-F0-9]+") |
| 104 | hex := re.FindString(raw) |
| 105 | |
| 106 | // Support short hex color form e.g. #fff, #121 |
| 107 | if len(hex) == 3 { |
| 108 | expanded := []byte{ |
| 109 | hex[0], hex[0], |
| 110 | hex[1], hex[1], |
| 111 | hex[2], hex[2]} |
| 112 | |
| 113 | hex = string(expanded) |
| 114 | } |
| 115 | |
| 116 | hex += "ffffff" |
| 117 | |
| 118 | red = stringToInt(hex[:2], 16) |
| 119 | green = stringToInt(hex[2:4], 16) |
| 120 | blue = stringToInt(hex[4:6], 16) |
| 121 | } |
| 122 | |
| 123 | return color{red, green, blue} |
| 124 | } |
| 125 | |
| 126 | func (c color) Hex() string { |
| 127 | return fmt.Sprintf("%02x%02x%02x", c.red, c.green, c.blue) |
no test coverage detected