initial commit [141.14.140.180,mike]

This commit is contained in:
mike committed 2026-10-22 13:21:28 +02:00
commit 156bb18c91
50 files changed
+13466

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
// Package colors parses colors the way Ghostty does: hex values (with or
// without a leading '#', 3 or 6 digits) and X11 color names.
package colors
import (
"bufio"
_ "embed"
"fmt"
"strconv"
"strings"
"sync"
)
// rgb.txt is copied from Ghostty's src/terminal/res/rgb.txt.
//
//go:embed rgb.txt
var rgbTxt string
var (
namesOnce sync.Once
names map[string]string // lowercase name -> "#rrggbb"
)
func loadNames() {
names = make(map[string]string, 800)
sc := bufio.NewScanner(strings.NewReader(rgbTxt))
for sc.Scan() {
line := sc.Text()
if strings.HasPrefix(line, "!") || strings.TrimSpace(line) == "" {
continue
}
fields := strings.Fields(line)
if len(fields) < 4 {
continue
}
r, err1 := strconv.Atoi(fields[0])
g, err2 := strconv.Atoi(fields[1])
b, err3 := strconv.Atoi(fields[2])
if err1 != nil || err2 != nil || err3 != nil {
continue
}
name := strings.ToLower(strings.Join(fields[3:], " "))
names[name] = fmt.Sprintf("#%02x%02x%02x", r, g, b)
}
}
// Hex converts a Ghostty color value to "#rrggbb". It reports false if the
// value is not a valid color.
func Hex(value string) (string, bool) {
v := strings.TrimSpace(unquote(value))
if v == "" {
return "", false
}
namesOnce.Do(loadNames)
if h, ok := names[strings.ToLower(v)]; ok {
return h, true
}
h := strings.TrimPrefix(v, "#")
if !isHex(h) {
return "", false
}
switch len(h) {
case 3:
return strings.ToLower("#" + string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]})), true
case 6:
return strings.ToLower("#" + h), true
}
return "", false
}
// Valid reports whether value is a color Ghostty accepts.
func Valid(value string) bool {
_, ok := Hex(value)
return ok
}
// RGB returns the components of a color value.
func RGB(value string) (r, g, b uint8, ok bool) {
h, ok := Hex(value)
if !ok {
return 0, 0, 0, false
}
n, err := strconv.ParseUint(h[1:], 16, 32)
if err != nil {
return 0, 0, 0, false
}
return uint8(n >> 16), uint8(n >> 8), uint8(n), true
}
// Luminance returns the relative brightness in the range 0..1, used to pick
// a readable text color on top of a swatch.
func Luminance(value string) float64 {
r, g, b, ok := RGB(value)
if !ok {
return 0
}
return (0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)) / 255
}
func isHex(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if !strings.ContainsRune("0123456789abcdefABCDEF", c) {
return false
}
}
return true
}
func unquote(s string) string {
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
return s
}