2013-03-13 03:29:40 -04:00
|
|
|
package term
|
2013-02-13 20:10:00 -05:00
|
|
|
|
|
|
|
import (
|
2013-05-14 18:37:35 -04:00
|
|
|
"os"
|
|
|
|
"os/signal"
|
2013-02-13 20:10:00 -05:00
|
|
|
"syscall"
|
|
|
|
"unsafe"
|
|
|
|
)
|
|
|
|
|
|
|
|
type State struct {
|
2013-02-26 20:26:46 -05:00
|
|
|
termios Termios
|
2013-02-13 20:10:00 -05:00
|
|
|
}
|
|
|
|
|
2013-05-24 17:44:16 -04:00
|
|
|
type Winsize struct {
|
|
|
|
Width uint16
|
|
|
|
Height uint16
|
|
|
|
x uint16
|
|
|
|
y uint16
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetWinsize(fd uintptr) (*Winsize, error) {
|
|
|
|
ws := &Winsize{}
|
|
|
|
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws)))
|
|
|
|
return ws, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func SetWinsize(fd uintptr, ws *Winsize) error {
|
|
|
|
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws)))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2013-02-13 20:10:00 -05:00
|
|
|
// IsTerminal returns true if the given file descriptor is a terminal.
|
2013-06-01 18:55:05 -04:00
|
|
|
func IsTerminal(fd uintptr) bool {
|
2013-02-26 20:26:46 -05:00
|
|
|
var termios Termios
|
2013-06-01 18:55:05 -04:00
|
|
|
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&termios)))
|
2013-02-26 20:26:46 -05:00
|
|
|
return err == 0
|
2013-02-13 20:10:00 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Restore restores the terminal connected to the given file descriptor to a
|
|
|
|
// previous state.
|
2013-06-01 18:55:05 -04:00
|
|
|
func Restore(fd uintptr, state *State) error {
|
|
|
|
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&state.termios)))
|
2013-02-26 20:26:46 -05:00
|
|
|
return err
|
2013-02-13 20:10:00 -05:00
|
|
|
}
|
2013-05-14 18:37:35 -04:00
|
|
|
|
|
|
|
func SetRawTerminal() (*State, error) {
|
2013-06-01 18:55:05 -04:00
|
|
|
oldState, err := MakeRaw(os.Stdin.Fd())
|
2013-05-14 18:37:35 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
c := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(c, os.Interrupt)
|
|
|
|
go func() {
|
|
|
|
_ = <-c
|
2013-06-01 18:55:05 -04:00
|
|
|
Restore(os.Stdin.Fd(), oldState)
|
2013-05-14 18:37:35 -04:00
|
|
|
os.Exit(0)
|
|
|
|
}()
|
|
|
|
return oldState, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func RestoreTerminal(state *State) {
|
2013-06-01 18:55:05 -04:00
|
|
|
Restore(os.Stdin.Fd(), state)
|
2013-05-14 18:37:35 -04:00
|
|
|
}
|