2024-03-05 16:47:02 +00:00
|
|
|
package color
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2024-03-05 23:18:51 +00:00
|
|
|
// Value is a type definition for the data type of a single color component.
|
|
|
|
type Value = float64
|
2024-03-05 16:47:02 +00:00
|
|
|
|
|
|
|
// Color represents an RGB color.
|
|
|
|
type Color struct {
|
2024-03-05 23:18:51 +00:00
|
|
|
R Value
|
|
|
|
G Value
|
|
|
|
B Value
|
2024-03-05 16:47:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// RGB creates a new color with red, green and blue values in the range of 0.0 to 1.0.
|
2024-03-05 23:18:51 +00:00
|
|
|
func RGB(r Value, g Value, b Value) Color {
|
2024-03-05 16:47:02 +00:00
|
|
|
return Color{r, g, b}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fprint writes the text in the given color to the writer.
|
2024-03-11 21:08:28 +00:00
|
|
|
func (c Color) Fprint(writer io.Writer, args ...any) {
|
2024-03-05 16:47:02 +00:00
|
|
|
if !Terminal {
|
2024-03-11 21:08:28 +00:00
|
|
|
fmt.Fprint(writer, args...)
|
2024-03-05 18:10:27 +00:00
|
|
|
return
|
2024-03-05 16:47:02 +00:00
|
|
|
}
|
|
|
|
|
2024-03-11 21:08:28 +00:00
|
|
|
fmt.Fprintf(writer, "\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
|
2024-03-05 16:47:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Print writes the text in the given color to standard output.
|
2024-03-11 21:08:28 +00:00
|
|
|
func (c Color) Print(args ...any) {
|
2024-03-05 16:47:02 +00:00
|
|
|
if !Terminal {
|
2024-03-11 21:08:28 +00:00
|
|
|
fmt.Print(args...)
|
2024-03-05 18:10:27 +00:00
|
|
|
return
|
2024-03-05 16:47:02 +00:00
|
|
|
}
|
|
|
|
|
2024-03-11 21:08:28 +00:00
|
|
|
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
|
|
|
|
}
|
|
|
|
|
2024-03-11 22:28:37 +00:00
|
|
|
// Printf formats according to a format specifier and writes the text in the given color to standard output.
|
2024-03-11 21:08:28 +00:00
|
|
|
func (c Color) Printf(format string, args ...any) {
|
|
|
|
if !Terminal {
|
|
|
|
fmt.Printf(format, args...)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprintf(format, args...))
|
2024-03-05 16:47:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Println writes the text in the given color to standard output and appends a newline.
|
2024-03-11 21:08:28 +00:00
|
|
|
func (c Color) Println(args ...any) {
|
2024-03-05 16:47:02 +00:00
|
|
|
if !Terminal {
|
2024-03-11 21:08:28 +00:00
|
|
|
fmt.Println(args...)
|
2024-03-05 18:10:27 +00:00
|
|
|
return
|
2024-03-05 16:47:02 +00:00
|
|
|
}
|
|
|
|
|
2024-03-11 21:08:28 +00:00
|
|
|
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\n\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
|
2024-03-05 16:47:02 +00:00
|
|
|
}
|