hlctl/ctllog/colors.go

102 lines
1.5 KiB
Go

package ctllog
import (
"encoding/hex"
"fmt"
)
// \x1b[38;2;255;100;0mTRUECOLOR\x1b[0m
// ESC[ 38;2;⟨r⟩;⟨g⟩;⟨b⟩ m Select RGB foreground color
const (
escape byte = 0x1B
csi byte = '['
separator byte = ';'
csiEnd byte = 'm'
fgColor byte = '3'
bgColor byte = '4'
trueColor byte = '8'
rgb byte = '2'
reset byte = '0'
)
var (
trueColorFMT = string([]byte{
escape,
csi,
'%', 'c',
trueColor,
separator,
rgb,
separator,
'%', 'd',
separator,
'%', 'd',
separator,
'%', 'd',
csiEnd,
'%', 's',
escape,
csi,
reset,
csiEnd,
})
)
type Variant byte
const (
Foreground = Variant(fgColor)
Background = Variant(bgColor)
)
type ColorRGB struct {
r uint8
g uint8
b uint8
}
func (ColorRGB) FromHex(hexString string) ColorRGB {
if len(hexString) < 6 {
return White
}
if hexString[0] == '#' {
hexString = hexString[1:]
}
if len(hexString) != 6 {
return White
}
res, err := hex.DecodeString(hexString)
if err != nil {
fmt.Println(err.Error())
return White
}
return ColorRGB{
r: res[0],
g: res[1],
b: res[2],
}
}
func getStr(str string, typeByte Variant, color ColorRGB) string {
return fmt.Sprintf(
trueColorFMT,
typeByte,
color.r,
color.g,
color.b,
str,
)
}
var (
Black ColorRGB
White = ColorRGB{255, 255, 255}
Green = ColorRGB{0, 255, 0}
Red = ColorRGB{255, 0, 0}
Blue = ColorRGB{0, 0, 255}
Purple = ColorRGB{255, 0, 255}
Yellow = ColorRGB{255, 255, 0}
)