go-prompt/_tools/window_size.go

81 lines
1.4 KiB
Go
Raw Normal View History

2017-07-06 16:00:35 +00:00
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"unsafe"
)
2018-02-02 16:16:25 +00:00
// Winsize is winsize struct got from the ioctl(2) system call.
type Winsize struct {
2017-07-06 16:00:35 +00:00
Row uint16
Col uint16
X uint16 // pixel value
Y uint16 // pixel value
}
// GetWinSize returns winsize struct which is the response of ioctl(2).
2018-02-02 16:16:25 +00:00
func GetWinSize(fd int) *Winsize {
ws := &Winsize{}
2017-07-06 16:00:35 +00:00
retCode, _, errno := syscall.Syscall(
syscall.SYS_IOCTL,
uintptr(fd),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws)))
if int(retCode) == -1 {
panic(errno)
}
2018-02-02 16:16:25 +00:00
return ws
2017-07-06 16:00:35 +00:00
}
func main() {
2018-02-02 16:16:25 +00:00
signalChan := make(chan os.Signal, 1)
2017-07-06 16:00:35 +00:00
signal.Notify(
2018-02-02 16:16:25 +00:00
signalChan,
2017-07-06 16:00:35 +00:00
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGWINCH,
)
2018-02-02 16:16:25 +00:00
ws := GetWinSize(syscall.Stdin)
fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
2017-07-06 16:00:35 +00:00
2018-02-02 16:16:25 +00:00
exitChan := make(chan int)
2017-07-06 16:00:35 +00:00
go func() {
for {
2018-02-02 16:16:25 +00:00
s := <-signalChan
2017-07-06 16:00:35 +00:00
switch s {
// kill -SIGHUP XXXX
case syscall.SIGHUP:
2018-02-02 16:16:25 +00:00
exitChan <- 0
2017-07-06 16:00:35 +00:00
// kill -SIGINT XXXX or Ctrl+c
case syscall.SIGINT:
2018-02-02 16:16:25 +00:00
exitChan <- 0
2017-07-06 16:00:35 +00:00
// kill -SIGTERM XXXX
case syscall.SIGTERM:
2018-02-02 16:16:25 +00:00
exitChan <- 0
2017-07-06 16:00:35 +00:00
// kill -SIGQUIT XXXX
case syscall.SIGQUIT:
2018-02-02 16:16:25 +00:00
exitChan <- 0
2017-07-06 16:00:35 +00:00
case syscall.SIGWINCH:
2018-02-02 16:16:25 +00:00
ws := GetWinSize(syscall.Stdin)
fmt.Printf("Row %d : Col %d\n", ws.Row, ws.Col)
2017-07-06 16:00:35 +00:00
default:
2018-02-02 16:16:25 +00:00
exitChan <- 1
2017-07-06 16:00:35 +00:00
}
}
}()
2018-02-02 16:16:25 +00:00
code := <-exitChan
2017-07-06 16:00:35 +00:00
os.Exit(code)
}