| 1 |
//go:build (linux || darwin || freebsd || netbsd || openbsd || solaris || dragonfly) && !appengine |
| 2 |
// +build linux darwin freebsd netbsd openbsd solaris dragonfly |
| 3 |
// +build !appengine |
| 4 |
|
| 5 |
package termutil |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"os" |
| 10 |
"syscall" |
| 11 |
"unsafe" |
| 12 |
) |
| 13 |
|
| 14 |
var ( |
| 15 |
tty *os.File |
| 16 |
|
| 17 |
unlockSignals = []os.Signal{ |
| 18 |
os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL, |
| 19 |
} |
| 20 |
oldState syscall.Termios |
| 21 |
) |
| 22 |
|
| 23 |
type window struct { |
| 24 |
Row uint16 |
| 25 |
Col uint16 |
| 26 |
Xpixel uint16 |
| 27 |
Ypixel uint16 |
| 28 |
} |
| 29 |
|
| 30 |
func init() { |
| 31 |
var err error |
| 32 |
tty, err = os.Open("/dev/tty") |
| 33 |
if err != nil { |
| 34 |
tty = os.Stdin |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
// TerminalWidth returns width of the terminal. |
| 39 |
func TerminalWidth() (int, error) { |
| 40 |
_, c, err := TerminalSize() |
| 41 |
return c, err |
| 42 |
} |
| 43 |
|
| 44 |
// TerminalSize returns size of the terminal. |
| 45 |
func TerminalSize() (rows, cols int, err error) { |
| 46 |
w := new(window) |
| 47 |
res, _, err := syscall.Syscall(sysIoctl, |
| 48 |
tty.Fd(), |
| 49 |
uintptr(syscall.TIOCGWINSZ), |
| 50 |
uintptr(unsafe.Pointer(w)), |
| 51 |
) |
| 52 |
if int(res) == -1 { |
| 53 |
return 0, 0, err |
| 54 |
} |
| 55 |
return int(w.Row), int(w.Col), nil |
| 56 |
} |
| 57 |
|
| 58 |
func lockEcho() error { |
| 59 |
fd := tty.Fd() |
| 60 |
|
| 61 |
if _, _, err := syscall.Syscall(sysIoctl, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&oldState))); err != 0 { |
| 62 |
return fmt.Errorf("error when puts the terminal connected to the given file descriptor: %w", err) |
| 63 |
} |
| 64 |
|
| 65 |
newState := oldState |
| 66 |
newState.Lflag &^= syscall.ECHO |
| 67 |
newState.Lflag |= syscall.ICANON | syscall.ISIG |
| 68 |
newState.Iflag |= syscall.ICRNL |
| 69 |
if _, _, e := syscall.Syscall(sysIoctl, fd, ioctlWriteTermios, uintptr(unsafe.Pointer(&newState))); e != 0 { |
| 70 |
return fmt.Errorf("error update terminal settings: %w", e) |
| 71 |
} |
| 72 |
return nil |
| 73 |
} |
| 74 |
|
| 75 |
func unlockEcho() error { |
| 76 |
fd := tty.Fd() |
| 77 |
if _, _, err := syscall.Syscall(sysIoctl, fd, ioctlWriteTermios, uintptr(unsafe.Pointer(&oldState))); err != 0 { |
| 78 |
return fmt.Errorf("error restores the terminal connected to the given file descriptor: %w", err) |
| 79 |
} |
| 80 |
return nil |
| 81 |
} |