Debian Codegraph @

src/tui/light_unix.go

raw
1 //go:build !windows
2
3 package tui
4
5 import (
6 "errors"
7 "os"
8 "os/exec"
9 "strings"
10 "syscall"
11 "time"
12
13 "github.com/junegunn/fzf/src/util"
14 "golang.org/x/sys/unix"
15 "golang.org/x/term"
16 )
17
18 func IsLightRendererSupported() bool {
19 return true
20 }
21
22 func (r *LightRenderer) DefaultTheme() *ColorTheme {
23 if strings.Contains(os.Getenv("TERM"), "256") {
24 return Dark256
25 }
26 colors, err := exec.Command("tput", "colors").Output()
27 if err == nil && atoi(strings.TrimSpace(string(colors)), 16) > 16 {
28 return Dark256
29 }
30 return Default16
31 }
32
33 func (r *LightRenderer) fd() int {
34 return int(r.ttyin.Fd())
35 }
36
37 func (r *LightRenderer) initPlatform() (err error) {
38 r.origState, err = term.MakeRaw(r.fd())
39 return err
40 }
41
42 func (r *LightRenderer) closePlatform() {
43 r.ttyout.Close()
44 }
45
46 func openTty(ttyDefault string, mode int) (*os.File, error) {
47 var in *os.File
48 var err error
49 if len(ttyDefault) > 0 {
50 in, err = os.OpenFile(ttyDefault, mode, 0)
51 }
52 if in == nil || err != nil || ttyDefault != DefaultTtyDevice && !util.IsTty(in) {
53 tty := ttyname()
54 if len(tty) > 0 {
55 if in, err := os.OpenFile(tty, mode, 0); err == nil {
56 return in, nil
57 }
58 }
59 if ttyDefault != DefaultTtyDevice {
60 if in, err = os.OpenFile(DefaultTtyDevice, mode, 0); err == nil {
61 return in, nil
62 }
63 }
64 return nil, errors.New("failed to open " + DefaultTtyDevice)
65 }
66 return in, nil
67 }
68
69 func openTtyIn(ttyDefault string) (*os.File, error) {
70 return openTty(ttyDefault, syscall.O_RDONLY)
71 }
72
73 func openTtyOut(ttyDefault string) (*os.File, error) {
74 return openTty(ttyDefault, syscall.O_WRONLY)
75 }
76
77 func (r *LightRenderer) setupTerminal() {
78 term.MakeRaw(r.fd())
79 }
80
81 func (r *LightRenderer) restoreTerminal() {
82 term.Restore(r.fd(), r.origState)
83 }
84
85 func (r *LightRenderer) updateTerminalSize() {
86 width, height, err := term.GetSize(r.fd())
87
88 if err == nil {
89 r.width = width
90 r.height = r.maxHeightFunc(height)
91 } else {
92 r.width = getEnv("COLUMNS", defaultWidth)
93 r.height = r.maxHeightFunc(getEnv("LINES", defaultHeight))
94 }
95 }
96
97 // waitReadable reports whether the tty has something to read before the
98 // deadline. A terminal that does not recognize a query answers nothing at all,
99 // so the read that follows must be able to stop waiting, or fzf would wait for
100 // the user to press a key instead of drawing itself. The timeout is generous
101 // because a terminal that does answer exceeds it only when the link is slow
102 // enough to be unusable anyway.
103 func (r *LightRenderer) waitReadable(timeout time.Duration) bool {
104 fd := r.fd()
105 deadline := time.Now().Add(timeout)
106 for {
107 remaining := time.Until(deadline)
108 if remaining <= 0 {
109 return false
110 }
111 var rfds unix.FdSet
112 if fd >= len(rfds.Bits)*unix.NFDBITS {
113 return false
114 }
115 rfds.Set(fd)
116 // Recomputed each time round: Linux select rewrites the timeout with
117 // the time left, other systems leave it alone
118 tv := unix.NsecToTimeval(int64(remaining))
119 n, err := unix.Select(fd+1, &rfds, nil, nil, &tv)
120 if err == syscall.EINTR {
121 continue
122 }
123 if err != nil {
124 // Nothing was confirmed readable, and the read that follows
125 // reports the failure if the fd is really broken
126 return false
127 }
128 return n > 0
129 }
130 }
131
132 // queryTerminal sends every query in a single write and reads until the last
133 // one is answered. Returns the submatches of each reply, nil for a query the
134 // terminal ignored. Replies are cut out of what we read as they are recognized,
135 // so whatever is left over is input the user typed during the round trip.
136 func (r *LightRenderer) queryTerminal(queries []termQuery) [][][]byte {
137 for _, query := range queries {
138 r.csi(query.seq)
139 }
140 r.flush()
141
142 replies := make([][][]byte, len(queries))
143 buffer := []byte{}
144 for tries := range offsetPollTries {
145 // Only the first read blocks, so that is the one to put a bound on
146 if tries == 0 && !r.waitReadable(queryTimeout) {
147 return replies
148 }
149
150 var err error
151 buffer, _, err = r.getBytesInternal(false, buffer, tries > 0)
152 if err != nil {
153 return replies
154 }
155
156 for idx, query := range queries {
157 if replies[idx] != nil {
158 continue
159 }
160 loc := query.reply.FindSubmatchIndex(buffer)
161 if loc == nil {
162 continue
163 }
164 groups := make([][]byte, len(loc)/2)
165 for group := range groups {
166 if loc[group*2] >= 0 {
167 groups[group] = buffer[loc[group*2]:loc[group*2+1]]
168 }
169 }
170 replies[idx] = groups
171 // Capping the prefix makes append copy, leaving groups valid
172 buffer = append(buffer[:loc[0]:loc[0]], buffer[loc[1]:]...)
173 }
174
175 if replies[len(queries)-1] != nil {
176 break
177 }
178 }
179
180 r.buffer = append(r.buffer, buffer...)
181 return replies
182 }
183
184 func (r *LightRenderer) queryStartup() (row int, col int, pasteWasSet *bool) {
185 replies := r.queryTerminal(startupQueries)
186 before, paste, after := replies[0], replies[1], replies[2]
187
188 if paste != nil && paste[1][0] != '0' {
189 // 1 = set, 3 = permanently set
190 set := paste[1][0] == '1' || paste[1][0] == '3'
191 pasteWasSet = &set
192 }
193 row, col = parseOffset(before)
194
195 // The cursor moved right likely because terminal doesn't support DECRQM
196 if row2, col2 := parseOffset(after); row >= 0 && row2 == row && col2 > col {
197 r.flushRaw(strings.Repeat("\b \b", col2-col))
198 }
199 return
200 }
201
202 func parseOffset(reply [][]byte) (row int, col int) {
203 if reply == nil {
204 return -1, -1
205 }
206 return atoi(string(reply[1]), 0) - 1, atoi(string(reply[2]), 0) - 1
207 }
208
209 func (r *LightRenderer) findOffset() (row int, col int) {
210 return parseOffset(r.queryTerminal([]termQuery{offsetQuery})[0])
211 }
212
213 func (r *LightRenderer) getch(cancellable bool, nonblock bool) (int, getCharResult) {
214 fd := r.fd()
215 getter := func() (int, getCharResult) {
216 b := make([]byte, 1)
217 util.SetNonblock(r.ttyin, nonblock)
218 _, err := util.Read(fd, b)
219 if err != nil {
220 return 0, getCharError
221 }
222 return int(b[0]), getCharSuccess
223 }
224 if nonblock || !cancellable {
225 return getter()
226 }
227
228 rpipe, wpipe, err := os.Pipe()
229 if err != nil {
230 // Fallback to blocking read without cancellation
231 return getter()
232 }
233 r.setCancel(func() {
234 wpipe.Write([]byte{0})
235 })
236 defer func() {
237 r.setCancel(nil)
238 rpipe.Close()
239 wpipe.Close()
240 }()
241
242 cancelFd := int(rpipe.Fd())
243 for {
244 var rfds unix.FdSet
245 limit := len(rfds.Bits) * unix.NFDBITS
246 if fd >= limit || cancelFd >= limit {
247 return getter()
248 }
249
250 rfds.Set(fd)
251 rfds.Set(cancelFd)
252 _, err := unix.Select(max(fd, cancelFd)+1, &rfds, nil, nil, nil)
253 if err != nil {
254 // An interrupted wait is not a failed read, so it must not count
255 // against anything. Retry until the fd is ready or the wait fails.
256 if err == syscall.EINTR {
257 continue
258 }
259 return 0, getCharError
260 }
261
262 if rfds.IsSet(cancelFd) {
263 return 0, getCharCancelled
264 }
265
266 if rfds.IsSet(fd) {
267 return getter()
268 }
269 }
270 }
271
272 func (r *LightRenderer) Size() TermSize {
273 ws, err := unix.IoctlGetWinsize(int(r.ttyin.Fd()), unix.TIOCGWINSZ)
274 if err != nil {
275 return TermSize{}
276 }
277 return TermSize{int(ws.Row), int(ws.Col), int(ws.Xpixel), int(ws.Ypixel)}
278 }