util.go 2.3 KB

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