github.com/jlowellwofford/u-root@v1.0.0/pkg/termios/termios_linux.go (about)

     1  // Copyright 2015-2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package termios
     6  
     7  import (
     8  	"os"
     9  
    10  	"golang.org/x/sys/unix"
    11  )
    12  
    13  // TTY is a wrapper that only allows Read and Write.
    14  type TTY struct {
    15  	f *os.File
    16  }
    17  
    18  func New() (*TTY, error) {
    19  	f, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	return &TTY{f: f}, nil
    24  }
    25  
    26  func (t *TTY) Read(b []byte) (int, error) {
    27  	return t.f.Read(b)
    28  }
    29  
    30  func (t *TTY) Write(b []byte) (int, error) {
    31  	return t.f.Write(b)
    32  }
    33  
    34  func GetTermios(fd uintptr) (*unix.Termios, error) {
    35  	return unix.IoctlGetTermios(int(fd), unix.TCGETS)
    36  }
    37  
    38  func (t *TTY) Get() (*unix.Termios, error) {
    39  	return GetTermios(t.f.Fd())
    40  }
    41  
    42  func SetTermios(fd uintptr, ti *unix.Termios) error {
    43  	return unix.IoctlSetTermios(int(fd), unix.TCSETS, ti)
    44  }
    45  
    46  func (t *TTY) Set(ti *unix.Termios) error {
    47  	return SetTermios(t.f.Fd(), ti)
    48  }
    49  
    50  func GetWinSize(fd uintptr) (*unix.Winsize, error) {
    51  	return unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ)
    52  }
    53  
    54  func (t *TTY) GetWinSize() (*unix.Winsize, error) {
    55  	return GetWinSize(t.f.Fd())
    56  }
    57  
    58  func SetWinSize(fd uintptr, w *unix.Winsize) error {
    59  	return unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, w)
    60  }
    61  
    62  func (t *TTY) SetWinSize(w *unix.Winsize) error {
    63  	return SetWinSize(t.f.Fd(), w)
    64  }
    65  
    66  func MakeRaw(term *unix.Termios) *unix.Termios {
    67  	raw := *term
    68  	raw.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
    69  	raw.Oflag &^= unix.OPOST
    70  	raw.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
    71  	raw.Cflag &^= unix.CSIZE | unix.PARENB
    72  	raw.Cflag |= unix.CS8
    73  
    74  	raw.Cc[unix.VMIN] = 1
    75  	raw.Cc[unix.VTIME] = 0
    76  
    77  	return &raw
    78  }