1package tui
2
3import (
4 "fmt"
5 "os"
6 "strconv"
7 "strings"
8 "time"
9
10 "golang.org/x/term"
11)
12
13// DetectThemeFromBackground queries the controlling tty for its
14// current background colour using the OSC 11 escape sequence and
15// returns Dark or Light based on the response's perceived
16// luminance. Falls back to Dark when the terminal does not
17// reply within timeout, which is the expected behaviour for
18// terminals that do not implement OSC 11 (Linux console, VS Code's
19// integrated terminal in some configurations, tmux without
20// pass-through, very old emulators).
21//
22// The query / parse runs synchronously before the TUI is
23// initialised so the returned theme can drive the entire session.
24// We briefly put stdin into raw mode and disable echo so the OSC
25// reply doesn't leak onto the user's screen as visible bytes.
26func DetectThemeFromBackground(timeout time.Duration) Theme {
27 // Honour explicit override env var first; some users / CI envs
28 // know better than the heuristic.
29 switch strings.ToLower(strings.TrimSpace(os.Getenv("ZOT_THEME"))) {
30 case "dark":
31 return Dark
32 case "light":
33 return Light
34 }
35
36 if !term.IsTerminal(int(os.Stdin.Fd())) || !term.IsTerminal(int(os.Stdout.Fd())) {
37 return Dark
38 }
39
40 fd := int(os.Stdin.Fd())
41 st, err := term.MakeRaw(fd)
42 if err != nil {
43 return Dark
44 }
45 defer term.Restore(fd, st)
46
47 // Send the query. ST (\x1b\\) and BEL (\x07) are both accepted
48 // terminators; some terminals only honour one of them, so we
49 // send BEL which is more widely supported.
50 if _, err := os.Stdout.Write([]byte("\x1b]11;?\x07")); err != nil {
51 return Dark
52 }
53
54 deadline := time.Now().Add(timeout)
55 resp := readOSCResponse(deadline)
56 if resp == "" {
57 return Dark
58 }
59
60 r, g, b, ok := parseOSC11Reply(resp)
61 if !ok {
62 return Dark
63 }
64
65 // Rec. 709 luma. Threshold at 0.5: anything brighter than
66 // mid-grey gets the light theme.
67 luma := 0.2126*float64(r) + 0.7152*float64(g) + 0.0722*float64(b)
68 if luma >= 0.5 {
69 return Light
70 }
71 return Dark
72}
73
74// readOSCResponse drains stdin into a small buffer until either a
75// terminator (BEL or ST) is seen, the deadline expires, or stdin
76// hits EOF. Returns whatever was collected, or "" on no usable
77// response.
78func readOSCResponse(deadline time.Time) string {
79 var buf [128]byte
80 n := 0
81 for time.Now().Before(deadline) {
82 remaining := time.Until(deadline)
83 if remaining <= 0 {
84 break
85 }
86 b, ok, err := peekStdin(os.Stdin, remaining)
87 if err != nil || !ok {
88 return string(buf[:n])
89 }
90 if n < len(buf) {
91 buf[n] = b
92 n++
93 }
94 // BEL terminator
95 if b == 0x07 {
96 return string(buf[:n])
97 }
98 // ST terminator: ESC then '\\'. We saw it the moment the
99 // previous byte was ESC and the current byte is '\\'.
100 if n >= 2 && buf[n-2] == 0x1b && buf[n-1] == '\\' {
101 return string(buf[:n])
102 }
103 }
104 return string(buf[:n])
105}
106
107// parseOSC11Reply extracts the (r, g, b) colour components from an
108// OSC 11 reply of the form "\x1b]11;rgb:RRRR/GGGG/BBBB\x07" (or with
109// ST terminator). The component widths can be 1, 2, 3, or 4 hex
110// digits per channel; we normalise them into the 0..1 range.
111func parseOSC11Reply(s string) (float64, float64, float64, bool) {
112 // Locate "rgb:" within the response.
113 i := strings.Index(s, "rgb:")
114 if i < 0 {
115 return 0, 0, 0, false
116 }
117 body := s[i+len("rgb:"):]
118 // Trim trailing terminator(s).
119 body = strings.TrimRight(body, "\x07")
120 if strings.HasSuffix(body, "\x1b\\") {
121 body = strings.TrimSuffix(body, "\x1b\\")
122 }
123 parts := strings.Split(body, "/")
124 if len(parts) != 3 {
125 return 0, 0, 0, false
126 }
127 parse := func(hexstr string) (float64, bool) {
128 if len(hexstr) == 0 || len(hexstr) > 4 {
129 return 0, false
130 }
131 v, err := strconv.ParseUint(hexstr, 16, 32)
132 if err != nil {
133 return 0, false
134 }
135 // Normalise to 0..1: max value is (16^len - 1).
136 max := uint64(1)
137 for j := 0; j < len(hexstr); j++ {
138 max *= 16
139 }
140 max--
141 if max == 0 {
142 return 0, false
143 }
144 return float64(v) / float64(max), true
145 }
146 r, ok1 := parse(parts[0])
147 g, ok2 := parse(parts[1])
148 b, ok3 := parse(parts[2])
149 if !ok1 || !ok2 || !ok3 {
150 return 0, 0, 0, false
151 }
152 return r, g, b, true
153}
154
155// debugDetect is used only in development to help diagnose
156// detection issues; never invoked in production code paths.
157func debugDetect() {
158 fmt.Fprintf(os.Stderr, "zot theme detection: stdin tty=%v stdout tty=%v\n",
159 term.IsTerminal(int(os.Stdin.Fd())),
160 term.IsTerminal(int(os.Stdout.Fd())))
161}