Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proceed with defaults if no OSC response arrives within 5 seconds #57

Merged
merged 1 commit into from Jan 31, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 35 additions & 8 deletions termenv_unix.go
Expand Up @@ -8,10 +8,16 @@ import (
"os"
"strconv"
"strings"
"time"

"golang.org/x/sys/unix"
)

const (
// timeout for OSC queries
OSCTimeout = 5 * time.Second
)

func colorProfile() Profile {
term := os.Getenv("TERM")
colorTerm := os.Getenv("COLORTERM")
Expand Down Expand Up @@ -84,7 +90,34 @@ func backgroundColor() Color {
return ANSIColor(0)
}

func waitForData(fd uintptr, timeout time.Duration) error {
tv := unix.NsecToTimeval(int64(timeout))
var readfds unix.FdSet
readfds.Set(int(fd))

for {
n, err := unix.Select(int(fd)+1, &readfds, nil, nil, &tv)
if err == unix.EINTR {
continue
}
if err != nil {
return err
}
if n == 0 {
return fmt.Errorf("timeout")
}

break
}

return nil
}

func readNextByte(f *os.File) (byte, error) {
if err := waitForData(f.Fd(), OSCTimeout); err != nil {
return 0, err
}

var b [1]byte
n, err := f.Read(b[:])
if err != nil {
Expand All @@ -107,20 +140,14 @@ func readNextResponse(fd *os.File) (response string, isOSC bool, err error) {
return "", false, err
}

// if we encounter a backslash, this is a left-over from the previous OSC
// response, which can be terminated by an optional backslash
if start == '\\' {
// first byte must be ESC
for start != '\033' {
start, err = readNextByte(fd)
if err != nil {
return "", false, err
}
}

// first byte must be ESC
if start != '\033' {
return "", false, ErrStatusReport
}

response += string(start)

// next byte is either '[' (cursor position response) or ']' (OSC response)
Expand Down