|
| 1 | +//go:build freebsd || openbsd |
| 2 | + |
| 3 | +package app |
| 4 | + |
| 5 | +import ( |
| 6 | + "time" |
| 7 | + |
| 8 | + "golang.org/x/sys/unix" |
| 9 | +) |
| 10 | + |
| 11 | +func isTerminal(fd uintptr) bool { |
| 12 | + _, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA) |
| 13 | + return err == nil |
| 14 | +} |
| 15 | + |
| 16 | +func makeRaw(fd uintptr) (*unix.Termios, error) { |
| 17 | + termios, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA) |
| 18 | + if err != nil { |
| 19 | + return nil, err |
| 20 | + } |
| 21 | + |
| 22 | + oldState := *termios |
| 23 | + |
| 24 | + termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON |
| 25 | + termios.Oflag &^= unix.OPOST |
| 26 | + termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN |
| 27 | + termios.Cflag &^= unix.CSIZE | unix.PARENB |
| 28 | + termios.Cflag |= unix.CS8 |
| 29 | + termios.Cc[unix.VMIN] = 1 |
| 30 | + termios.Cc[unix.VTIME] = 0 |
| 31 | + |
| 32 | + if err := unix.IoctlSetTermios(int(fd), unix.TIOCSETA, termios); err != nil { |
| 33 | + return nil, err |
| 34 | + } |
| 35 | + |
| 36 | + return &oldState, nil |
| 37 | +} |
| 38 | + |
| 39 | +func restoreTerminal(fd uintptr, oldState *unix.Termios) { |
| 40 | + if oldState != nil { |
| 41 | + _ = unix.IoctlSetTermios(int(fd), unix.TIOCSETA, oldState) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// queryTerminalSize gets the terminal columns and rows using TIOCGWINSZ |
| 46 | +func queryTerminalSize(caps *HostCapabilities) { |
| 47 | + ws, err := unix.IoctlGetWinsize(int(unix.Stdout), unix.TIOCGWINSZ) |
| 48 | + if err != nil { |
| 49 | + return |
| 50 | + } |
| 51 | + caps.Cols = int(ws.Col) |
| 52 | + caps.Rows = int(ws.Row) |
| 53 | + // Also get pixel dimensions if available |
| 54 | + if ws.Xpixel > 0 && caps.PixelWidth == 0 { |
| 55 | + caps.PixelWidth = int(ws.Xpixel) |
| 56 | + } |
| 57 | + if ws.Ypixel > 0 && caps.PixelHeight == 0 { |
| 58 | + caps.PixelHeight = int(ws.Ypixel) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +// pollReadable uses poll to wait for the file descriptor to be readable with a timeout |
| 63 | +func pollReadable(fd uintptr, timeout time.Duration) (bool, error) { |
| 64 | + fds := []unix.PollFd{ |
| 65 | + {Fd: int32(fd), Events: unix.POLLIN}, |
| 66 | + } |
| 67 | + timeoutMs := int(timeout.Milliseconds()) |
| 68 | + if timeoutMs < 1 { |
| 69 | + timeoutMs = 1 |
| 70 | + } |
| 71 | + |
| 72 | + n, err := unix.Poll(fds, timeoutMs) |
| 73 | + if err != nil { |
| 74 | + return false, err |
| 75 | + } |
| 76 | + return n > 0 && (fds[0].Revents&unix.POLLIN) != 0, nil |
| 77 | +} |
0 commit comments