| 1 |
package ansi |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"image/color" |
| 6 |
"strconv" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"github.com/lucasb-eyer/go-colorful" |
| 10 |
) |
| 11 |
|
| 12 |
// colorToHexString returns a hex string representation of a color. |
| 13 |
func colorToHexString(c color.Color) string { //nolint:unused |
| 14 |
if c == nil { |
| 15 |
return "" |
| 16 |
} |
| 17 |
shift := func(v uint32) uint32 { |
| 18 |
if v > 0xff { |
| 19 |
return v >> 8 |
| 20 |
} |
| 21 |
return v |
| 22 |
} |
| 23 |
r, g, b, _ := c.RGBA() |
| 24 |
r, g, b = shift(r), shift(g), shift(b) |
| 25 |
return fmt.Sprintf("#%02x%02x%02x", r, g, b) |
| 26 |
} |
| 27 |
|
| 28 |
// rgbToHex converts red, green, and blue values to a hexadecimal value. |
| 29 |
// |
| 30 |
// hex := rgbToHex(0, 0, 255) // 0x0000FF |
| 31 |
func rgbToHex(r, g, b uint32) uint32 { //nolint:unused |
| 32 |
return r<<16 + g<<8 + b |
| 33 |
} |
| 34 |
|
| 35 |
type shiftable interface { |
| 36 |
~uint | ~uint16 | ~uint32 | ~uint64 |
| 37 |
} |
| 38 |
|
| 39 |
func shift[T shiftable](x T) T { |
| 40 |
if x > 0xff { |
| 41 |
x >>= 8 |
| 42 |
} |
| 43 |
return x |
| 44 |
} |
| 45 |
|
| 46 |
// XParseColor is a helper function that parses a string into a color.Color. It |
| 47 |
// provides a similar interface to the XParseColor function in Xlib. It |
| 48 |
// supports the following formats: |
| 49 |
// |
| 50 |
// - #RGB |
| 51 |
// - #RRGGBB |
| 52 |
// - rgb:RRRR/GGGG/BBBB |
| 53 |
// - rgba:RRRR/GGGG/BBBB/AAAA |
| 54 |
// |
| 55 |
// If the string is not a valid color, nil is returned. |
| 56 |
// |
| 57 |
// See: https://linux.die.net/man/3/xparsecolor |
| 58 |
func XParseColor(s string) color.Color { |
| 59 |
switch { |
| 60 |
case strings.HasPrefix(s, "#"): |
| 61 |
c, err := colorful.Hex(s) |
| 62 |
if err != nil { |
| 63 |
return nil |
| 64 |
} |
| 65 |
|
| 66 |
return c |
| 67 |
case strings.HasPrefix(s, "rgb:"): |
| 68 |
parts := strings.Split(s[4:], "/") |
| 69 |
if len(parts) != 3 { |
| 70 |
return nil |
| 71 |
} |
| 72 |
|
| 73 |
r, _ := strconv.ParseUint(parts[0], 16, 32) |
| 74 |
g, _ := strconv.ParseUint(parts[1], 16, 32) |
| 75 |
b, _ := strconv.ParseUint(parts[2], 16, 32) |
| 76 |
|
| 77 |
return color.RGBA{uint8(shift(r)), uint8(shift(g)), uint8(shift(b)), 255} //nolint:gosec |
| 78 |
case strings.HasPrefix(s, "rgba:"): |
| 79 |
parts := strings.Split(s[5:], "/") |
| 80 |
if len(parts) != 4 { |
| 81 |
return nil |
| 82 |
} |
| 83 |
|
| 84 |
r, _ := strconv.ParseUint(parts[0], 16, 32) |
| 85 |
g, _ := strconv.ParseUint(parts[1], 16, 32) |
| 86 |
b, _ := strconv.ParseUint(parts[2], 16, 32) |
| 87 |
a, _ := strconv.ParseUint(parts[3], 16, 32) |
| 88 |
|
| 89 |
return color.RGBA{uint8(shift(r)), uint8(shift(g)), uint8(shift(b)), uint8(shift(a))} //nolint:gosec |
| 90 |
} |
| 91 |
return nil |
| 92 |
} |