elvish/sys/termios.go

78 lines
1.7 KiB
Go
Raw Normal View History

2015-02-26 23:58:24 +08:00
package sys
2014-09-28 00:17:55 +08:00
/*
#include <termios.h>
*/
import "C"
2016-01-29 10:11:01 +08:00
import "syscall"
2015-02-25 05:56:38 +08:00
// Termios represents terminal attributes.
type Termios C.struct_termios
2015-02-25 05:56:38 +08:00
// NewTermiosFromFd extracts the terminal attribute of the given file
// descriptor.
func NewTermiosFromFd(fd int) (*Termios, error) {
term := new(Termios)
err := term.FromFd(fd)
if err != nil {
return nil, err
}
return term, nil
}
func (term *Termios) c() *C.struct_termios {
return (*C.struct_termios)(term)
}
2015-02-25 05:56:38 +08:00
// FromFd fills term with the terminal attribute of the given file descriptor.
func (term *Termios) FromFd(fd int) error {
_, err := C.tcgetattr((C.int)(fd), term.c())
2014-09-28 00:17:55 +08:00
return err
}
2015-02-25 05:56:38 +08:00
// ApplyToFd applies term to the given file descriptor.
func (term *Termios) ApplyToFd(fd int) error {
_, err := C.tcsetattr((C.int)(fd), 0, term.c())
2014-09-28 00:17:55 +08:00
return err
}
2015-02-25 05:56:38 +08:00
// Copy returns a copy of term.
func (term *Termios) Copy() *Termios {
v := *term
return &v
}
2015-02-25 05:56:38 +08:00
// SetVTime sets the timeout in deciseconds for noncanonical read.
func (term *Termios) SetVTime(v uint8) {
term.c_cc[C.VTIME] = C.cc_t(v)
}
2015-02-25 05:56:38 +08:00
// SetVMin sets the minimal number of characters for noncanonical read.
func (term *Termios) SetVMin(v uint8) {
term.c_cc[C.VMIN] = C.cc_t(v)
}
func setFlag(flag *C.tcflag_t, mask C.tcflag_t, v bool) {
if v {
*flag |= mask
} else {
*flag &= ^mask
}
}
2015-02-25 05:56:38 +08:00
// SetICanon sets the canonical flag.
func (term *Termios) SetICanon(v bool) {
setFlag(&term.c_lflag, C.ICANON, v)
}
2015-02-25 05:56:38 +08:00
// SetEcho sets the echo flag.
func (term *Termios) SetEcho(v bool) {
setFlag(&term.c_lflag, C.ECHO, v)
}
2015-02-26 23:58:24 +08:00
// FlushInput discards data written to a file descriptor but not read.
func FlushInput(fd int) error {
_, err := C.tcflush((C.int)(fd), syscall.TCIFLUSH)
return err
}