Skip to content
Myr

light_unix.go

This file

Path

src/tui/light_unix.go

278 lines · 6.8 KiB · Go

Last changed by

Fix spurious exit while waiting for a key with --listenJunegunn Choibefore adoption1578b7c

History of this file

Take it

1//go:build !windows23package tui45import (6	"errors"7	"os"8	"os/exec"9	"strings"10	"syscall"11	"time"1213	"github.com/junegunn/fzf/src/util"14	"golang.org/x/sys/unix"15	"golang.org/x/term"16)1718func IsLightRendererSupported() bool {19	return true20}2122func (r *LightRenderer) DefaultTheme() *ColorTheme {23	if strings.Contains(os.Getenv("TERM"), "256") {24		return Dark25625	}26	colors, err := exec.Command("tput", "colors").Output()27	if err == nil && atoi(strings.TrimSpace(string(colors)), 16) > 16 {28		return Dark25629	}30	return Default1631}3233func (r *LightRenderer) fd() int {34	return int(r.ttyin.Fd())35}3637func (r *LightRenderer) initPlatform() (err error) {38	r.origState, err = term.MakeRaw(r.fd())39	return err40}4142func (r *LightRenderer) closePlatform() {43	r.ttyout.Close()44}4546func openTty(ttyDefault string, mode int) (*os.File, error) {47	var in *os.File48	var err error49	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, nil57			}58		}59		if ttyDefault != DefaultTtyDevice {60			if in, err = os.OpenFile(DefaultTtyDevice, mode, 0); err == nil {61				return in, nil62			}63		}64		return nil, errors.New("failed to open " + DefaultTtyDevice)65	}66	return in, nil67}6869func openTtyIn(ttyDefault string) (*os.File, error) {70	return openTty(ttyDefault, syscall.O_RDONLY)71}7273func openTtyOut(ttyDefault string) (*os.File, error) {74	return openTty(ttyDefault, syscall.O_WRONLY)75}7677func (r *LightRenderer) setupTerminal() {78	term.MakeRaw(r.fd())79}8081func (r *LightRenderer) restoreTerminal() {82	term.Restore(r.fd(), r.origState)83}8485func (r *LightRenderer) updateTerminalSize() {86	width, height, err := term.GetSize(r.fd())8788	if err == nil {89		r.width = width90		r.height = r.maxHeightFunc(height)91	} else {92		r.width = getEnv("COLUMNS", defaultWidth)93		r.height = r.maxHeightFunc(getEnv("LINES", defaultHeight))94	}95}9697// waitReadable reports whether the tty has something to read before the98// 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 for100// the user to press a key instead of drawing itself. The timeout is generous101// because a terminal that does answer exceeds it only when the link is slow102// enough to be unusable anyway.103func (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 false110		}111		var rfds unix.FdSet112		if fd >= len(rfds.Bits)*unix.NFDBITS {113			return false114		}115		rfds.Set(fd)116		// Recomputed each time round: Linux select rewrites the timeout with117		// the time left, other systems leave it alone118		tv := unix.NsecToTimeval(int64(remaining))119		n, err := unix.Select(fd+1, &rfds, nil, nil, &tv)120		if err == syscall.EINTR {121			continue122		}123		if err != nil {124			// Nothing was confirmed readable, and the read that follows125			// reports the failure if the fd is really broken126			return false127		}128		return n > 0129	}130}131132// queryTerminal sends every query in a single write and reads until the last133// one is answered. Returns the submatches of each reply, nil for a query the134// 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.136func (r *LightRenderer) queryTerminal(queries []termQuery) [][][]byte {137	for _, query := range queries {138		r.csi(query.seq)139	}140	r.flush()141142	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 on146		if tries == 0 && !r.waitReadable(queryTimeout) {147			return replies148		}149150		var err error151		buffer, _, err = r.getBytesInternal(false, buffer, tries > 0)152		if err != nil {153			return replies154		}155156		for idx, query := range queries {157			if replies[idx] != nil {158				continue159			}160			loc := query.reply.FindSubmatchIndex(buffer)161			if loc == nil {162				continue163			}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] = groups171			// Capping the prefix makes append copy, leaving groups valid172			buffer = append(buffer[:loc[0]:loc[0]], buffer[loc[1]:]...)173		}174175		if replies[len(queries)-1] != nil {176			break177		}178	}179180	r.buffer = append(r.buffer, buffer...)181	return replies182}183184func (r *LightRenderer) queryStartup() (row int, col int, pasteWasSet *bool) {185	replies := r.queryTerminal(startupQueries)186	before, paste, after := replies[0], replies[1], replies[2]187188	if paste != nil && paste[1][0] != '0' {189		// 1 = set, 3 = permanently set190		set := paste[1][0] == '1' || paste[1][0] == '3'191		pasteWasSet = &set192	}193	row, col = parseOffset(before)194195	// The cursor moved right likely because terminal doesn't support DECRQM196	if row2, col2 := parseOffset(after); row >= 0 && row2 == row && col2 > col {197		r.flushRaw(strings.Repeat("\b \b", col2-col))198	}199	return200}201202func parseOffset(reply [][]byte) (row int, col int) {203	if reply == nil {204		return -1, -1205	}206	return atoi(string(reply[1]), 0) - 1, atoi(string(reply[2]), 0) - 1207}208209func (r *LightRenderer) findOffset() (row int, col int) {210	return parseOffset(r.queryTerminal([]termQuery{offsetQuery})[0])211}212213func (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, getCharError221		}222		return int(b[0]), getCharSuccess223	}224	if nonblock || !cancellable {225		return getter()226	}227228	rpipe, wpipe, err := os.Pipe()229	if err != nil {230		// Fallback to blocking read without cancellation231		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	}()241242	cancelFd := int(rpipe.Fd())243	for {244		var rfds unix.FdSet245		limit := len(rfds.Bits) * unix.NFDBITS246		if fd >= limit || cancelFd >= limit {247			return getter()248		}249250		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 count255			// against anything. Retry until the fd is ready or the wait fails.256			if err == syscall.EINTR {257				continue258			}259			return 0, getCharError260		}261262		if rfds.IsSet(cancelFd) {263			return 0, getCharCancelled264		}265266		if rfds.IsSet(fd) {267			return getter()268		}269	}270}271272func (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}