Skip to content

Commit

Permalink
update some for color detect
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Apr 9, 2021
1 parent e298a5c commit ac48b1f
Show file tree
Hide file tree
Showing 12 changed files with 243 additions and 127 deletions.
1 change: 1 addition & 0 deletions color.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ func ForceOpenColor() terminfo.ColorLevel {
}

// IsLikeInCmd check result
// Deprecated
func IsLikeInCmd() bool {
return isLikeInCmd
}
Expand Down
33 changes: 26 additions & 7 deletions color_16.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
// Color Color16, 16 color value type
// 3(2^3=8) OR 4(2^4=16) bite color.
type Color uint8
type Basic = Color // alias of Color

// Opts basic color options. code: 0 - 9
type Opts []Color
Expand Down Expand Up @@ -145,6 +146,22 @@ const (
LightWhite = FgLightWhite
LightYellow = FgLightYellow
LightMagenta = FgLightMagenta

HiRed = FgLightRed
HiCyan = FgLightCyan
HiBlue = FgLightBlue
HiGreen = FgLightGreen
HiWhite = FgLightWhite
HiYellow = FgLightYellow
HiMagenta = FgLightMagenta

BgHiRed = BgLightRed
BgHiCyan = BgLightCyan
BgHiBlue = BgLightBlue
BgHiGreen = BgLightGreen
BgHiWhite = BgLightWhite
BgHiYellow = BgLightYellow
BgHiMagenta = BgLightMagenta
)

// Bit4 an method for create Color
Expand Down Expand Up @@ -258,18 +275,20 @@ func (c Color) C256() Color256 {
}

var isBg uint8

// basic color
if val >= BgBase && val <= 47 { // is bg
isBg = 1
isBg = AsBg
val = val - 10 // to fg code
} else if val >= HiBgBase && val <= 107 { // is bg
isBg = 1
} else if val >= HiBgBase && val <= 107 { // is hi bg
isBg = AsBg
val = val - 10 // to fg code
}

c256 := basicTo256Map[val]
return Color256{c256, isBg}
if c256, ok := basicTo256Map[val]; ok {
return Color256{c256, isBg}
}

// use raw value direct convert
return Color256{val}
}

// RGB convert 16 color to 256-color code.
Expand Down
17 changes: 17 additions & 0 deletions color_256.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ func (c Color256) Value() uint8 {
return c[0]
}

// Code convert to color code string. eg: "38;5;12"
func (c Color256) Code() string {
return c.String()
}

// String convert to color code string. eg: "38;5;12"
func (c Color256) String() string {
if c[1] == AsFg { // 0 is Fg
Expand All @@ -137,11 +142,23 @@ func (c Color256) IsFg() bool {
return c[1] == AsFg
}

// AsFg color
func (c Color256) AsFg() Color256 {
c[1] = AsFg
return c
}

// IsBg color
func (c Color256) IsBg() bool {
return c[1] == AsBg
}

// AsBg color
func (c Color256) AsBg() Color256 {
c[1] = AsBg
return c
}

// IsEmpty value
func (c Color256) IsEmpty() bool {
return c[1] > 1
Expand Down
1 change: 0 additions & 1 deletion color_rgb.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,6 @@ func (c RGBColor) Code() string {

// Hex color rgb to hex string. as in "ff0080".
func (c RGBColor) Hex() string {
// Add 0.5 for rounding
return fmt.Sprintf("%02x%02x%02x", c[0], c[1], c[2])
}

Expand Down
63 changes: 42 additions & 21 deletions color_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ func Example() {
Warn.Tips("tips style message")
}

var buf = new(bytes.Buffer)

/*************************************************************
* test global methods
*************************************************************/
Expand All @@ -66,7 +68,8 @@ func TestSet(t *testing.T) {
is := assert.New(t)

fmt.Println("support color:", SupportColor())
fmt.Println("test color.Set() on OS:", runtime.GOOS)
fmt.Println("color level:", TermColorLevel())
fmt.Println("current OS:", runtime.GOOS)

// disable
old := Disable()
Expand All @@ -81,14 +84,15 @@ func TestSet(t *testing.T) {

// set enable
Enable = true
if os.Getenv("GITHUB_ACTION") != "" {
fmt.Println("Skip run the tests on Github Action")
return
}
// if os.Getenv("GITHUB_ACTION") != "" {
// fmt.Println("--- Skip run the tests on Github Action")
// return
// }

num, err = Set(FgGreen)
is.True(num > 0)
is.Equal(0, num)
is.NoError(err)
fmt.Println("set fg is green")
_, err = Reset()
is.NoError(err)

Expand All @@ -101,23 +105,25 @@ func TestSet(t *testing.T) {
fmt.Println("- IsTerminal return FALSE")
}
} else {
is.True(IsTerminal(os.Stdout.Fd()))
is.False(IsLikeInCmd())
is.Empty(InnerErrs())
}

// set
rewriteStdout()
buf.Reset()
SetOutput(buf)
num, err = Set(FgGreen)
str := restoreStdout()
str := buf.String()
buf.Reset()

is.True(num > 0)
is.Equal(0, num)
is.NoError(err)
is.Equal("\x1b[32m", str)

// unset
rewriteStdout()
_, err = Reset()
str = restoreStdout()
str = buf.String()
is.NoError(err)
is.Equal("\x1b[0m", str)
}
Expand Down Expand Up @@ -268,6 +274,7 @@ func TestColor16(t *testing.T) {
str := Red.Sprintf("A %s", "MSG")
is.Equal("red", Red.Name())
is.Equal("\x1b[31mA MSG\x1b[0m", str)
is.Equal("unknown", Basic(123).Name())

// Color.Print
FgGray.Print("MSG")
Expand Down Expand Up @@ -325,7 +332,26 @@ func TestColor16(t *testing.T) {
is.True(ok)
}

func TestColor_C256(t *testing.T) {
assert.True(t, Bold.C256().IsEmpty())

Red.C256().Println("fg: basic to 256 color")
BgRed.C256().Println("bg: basic to 256 color")
assert.Equal(t, "38;5;160", Red.C256().Code())
assert.Equal(t, "48;5;160", BgRed.C256().Code())

LightCyan.C256().Println("fg: basic to 256 color")
BgHiCyan.C256().Println("bg: basic to 256 color")

assert.Equal(t, "38;5;203", LightRed.C256().Code())
assert.Equal(t, "48;5;203", BgLightRed.C256().Code())

Basic(167).C256().Println("invalid basic color code to 256")
}

func TestColor_RGB(t *testing.T) {
assert.True(t, Bold.RGB().IsEmpty())

fmt.Println("------- 16-color code:")
for u, s := range Basic2name {
if u < 10 { // is option
Expand All @@ -345,10 +371,6 @@ func TestColor_RGB(t *testing.T) {
}
}

func TestColor_C256(t *testing.T) {

}

func TestPrintBasicColor(t *testing.T) {
fmt.Println("Foreground colors:")
for name, c := range FgColors {
Expand Down Expand Up @@ -381,7 +403,7 @@ func TestPrintBasicColor(t *testing.T) {

func TestQuickFunc(t *testing.T) {
// inline func
testFuncs := []func(...interface{}) {
testFuncs := []func(...interface{}){
Redp,
Bluep,
Cyanp,
Expand All @@ -400,7 +422,7 @@ func TestQuickFunc(t *testing.T) {
fmt.Println()

// line func
testFuncs = []func(...interface{}) {
testFuncs = []func(...interface{}){
Redln,
Blueln,
Cyanln,
Expand Down Expand Up @@ -463,20 +485,20 @@ func TestColor256(t *testing.T) {
// Color256.Print
c.Print("MSG")
str = buf.String()
buf.Reset()
is.Equal("\x1b[38;5;132mMSG\x1b[0m", str)
buf.Reset()

// Color256.Printf
c.Printf("A %s", "MSG")
str = buf.String()
buf.Reset()
is.Equal("\x1b[38;5;132mA MSG\x1b[0m", str)
buf.Reset()

// Color256.Println
c.Println("MSG", "TEXT")
str = buf.String()
buf.Reset()
is.Equal("\x1b[38;5;132mMSG TEXT\x1b[0m\n", str)
buf.Reset()
}

func TestStyle256(t *testing.T) {
Expand Down Expand Up @@ -596,7 +618,6 @@ func forceOpenColorRender() *bytes.Buffer {
// set output for test
buf := new(bytes.Buffer)
SetOutput(buf)

return buf
}

Expand Down
42 changes: 22 additions & 20 deletions convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ var (
97: "ffffff", // lightWhite
}
// will convert data from basic2hexMap
hex2basicMap = initHex2basic()
hex2basicMap = initHex2basicMap()

// ---------- 256 <=> RGB color convert ----------
// adapted from https://gist.github.com/MicahElliott/719710

c256ToRgb = map[uint8]string{}
c256ToHexMap = init256ToHexMap()

// rgb to 256 color look-up table
// RGB hex => 256 code
Expand Down Expand Up @@ -338,6 +338,24 @@ var (
incs = []uint8{0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff}
)

func initHex2basicMap() map[string]uint8 {
h2b := make(map[string]uint8, len(basic2hexMap))
// ini data map
for u, s := range basic2hexMap {
h2b[s] = u
}
return h2b
}

func init256ToHexMap() map[uint8]string {
c256toh := make(map[uint8]string, len(hexTo256Table))
// ini data map
for hex, c256 := range hexTo256Table {
c256toh[c256] = hex
}
return c256toh
}

// RgbTo256Table mapping data
func RgbTo256Table() map[string]uint8 {
return hexTo256Table
Expand Down Expand Up @@ -450,15 +468,6 @@ func Rgb2basic(r, g, b uint8, isBg bool) uint8 {
return RgbToAnsi(r, g, b, isBg)
}

func initHex2basic() map[string]uint8 {
h2b := make(map[string]uint8, len(basic2hexMap))
// ini data map
for u, s := range basic2hexMap {
h2b[s] = u
}
return h2b
}

// Rgb2ansi alias of the RgbToAnsi()
func Rgb2ansi(r, g, b uint8, isBg bool) uint8 {
return RgbToAnsi(r, g, b, isBg)
Expand Down Expand Up @@ -504,7 +513,7 @@ func RgbToAnsi(r, g, b uint8, isBg bool) uint8 {
return base + bright + c
}

// Rgb2short convert RGB-code to 256-code
// RgbTo256 convert RGB-code to 256-code
func RgbTo256(r, g, b uint8) uint8 {
return Rgb2short(r, g, b)
}
Expand Down Expand Up @@ -538,14 +547,7 @@ func Rgb2short(r, g, b uint8) uint8 {

// C256ToRgb convert an 256 color code to RGB numbers
func C256ToRgb(val uint8) (rgb []uint8) {
// TODO use sync.Once
if len(c256ToRgb) == 0 {
for hex, c256 := range hexTo256Table {
c256ToRgb[c256] = hex
}
}

hex, ok := c256ToRgb[val]
hex, ok := c256ToHexMap[val]
if false == ok {
return
}
Expand Down
Loading

0 comments on commit ac48b1f

Please sign in to comment.