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 fileTake it
The walk stopped after 200 commits: lines older than 76efddd point at it.
bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 1–10why, one step back1//go:build !windows23package tui45import (6 "errors"7 "os"8 "os/exec"9 "strings"10 "syscall"Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
line 11why, one step back11 "time"bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 12–96why, one step back1213 "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}96Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 97–139why, one step back97// 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 }bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
line 140why, one step back140 r.flush()Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 141–143why, one step back141142 replies := make([][][]byte, len(queries))143 buffer := []byte{}bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
line 144why, one step back144 for tries := range offsetPollTries {Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 145–151why, one step back145 // 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)bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
line 152why, one step back152 if err != nil {Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
line 153why, one step back153 return repliesbash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 154–155why, one step back154 }155Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 156–172why, one step back156 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]:]...)bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
line 173why, one step back173 }Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 174–177why, one step back174175 if replies[len(queries)-1] != nil {176 break177 }bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
line 178why, one step back178 }Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 179–185why, one step back179180 r.buffer = append(r.buffer, buffer...)181 return replies182}183184func (r *LightRenderer) queryStartup() (row int, col int, pasteWasSet *bool) {185 replies := r.queryTerminal(startupQueries)Erase 'p' on Terminal.appJunegunn Choibefore adoptionca4c1b8
lines 186–188why, one step back186 before, paste, after := replies[0], replies[1], replies[2]187188 if paste != nil && paste[1][0] != '0' {Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 189–192why, one step back189 // 1 = set, 3 = permanently set190 set := paste[1][0] == '1' || paste[1][0] == '3'191 pasteWasSet = &set192 }Erase 'p' on Terminal.appJunegunn Choibefore adoptionca4c1b8
lines 193–198why, one step back193 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 }Restore bracketed paste mode instead of forcing it offJunegunn Choibefore adoptiondab626b
lines 199–209why, one step back199 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) {Erase 'p' on Terminal.appJunegunn Choibefore adoptionca4c1b8
line 210why, one step back210 return parseOffset(r.queryTerminal([]termQuery{offsetQuery})[0])bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 211–242why, one step back211}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())Fix spurious exit while waiting for a key with --listenJunegunn Choibefore adoption1578b7c
line 243why, one step back243 for {bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 244–253why, one step back244 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 {Fix spurious exit while waiting for a key with --listenJunegunn Choibefore adoption1578b7c
lines 254–255why, one step back254 // 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.bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 256–278why, one step back256 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}