term_unix.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //go:build !windows
  2. // +build !windows
  3. package term
  4. import (
  5. "errors"
  6. "io"
  7. "os"
  8. "golang.org/x/sys/unix"
  9. )
  10. // ErrInvalidState is returned if the state of the terminal is invalid.
  11. //
  12. // Deprecated: ErrInvalidState is no longer used.
  13. var ErrInvalidState = errors.New("Invalid terminal state")
  14. // terminalState holds the platform-specific state / console mode for the terminal.
  15. type terminalState struct {
  16. termios unix.Termios
  17. }
  18. func stdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) {
  19. return os.Stdin, os.Stdout, os.Stderr
  20. }
  21. func getFdInfo(in interface{}) (uintptr, bool) {
  22. var inFd uintptr
  23. var isTerminalIn bool
  24. if file, ok := in.(*os.File); ok {
  25. inFd = file.Fd()
  26. isTerminalIn = isTerminal(inFd)
  27. }
  28. return inFd, isTerminalIn
  29. }
  30. func getWinsize(fd uintptr) (*Winsize, error) {
  31. uws, err := unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ)
  32. ws := &Winsize{Height: uws.Row, Width: uws.Col, x: uws.Xpixel, y: uws.Ypixel}
  33. return ws, err
  34. }
  35. func setWinsize(fd uintptr, ws *Winsize) error {
  36. return unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, &unix.Winsize{
  37. Row: ws.Height,
  38. Col: ws.Width,
  39. Xpixel: ws.x,
  40. Ypixel: ws.y,
  41. })
  42. }
  43. func isTerminal(fd uintptr) bool {
  44. _, err := tcget(fd)
  45. return err == nil
  46. }
  47. func restoreTerminal(fd uintptr, state *State) error {
  48. if state == nil {
  49. return errors.New("invalid terminal state")
  50. }
  51. return tcset(fd, &state.termios)
  52. }
  53. func saveState(fd uintptr) (*State, error) {
  54. termios, err := tcget(fd)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return &State{termios: *termios}, nil
  59. }
  60. func disableEcho(fd uintptr, state *State) error {
  61. newState := state.termios
  62. newState.Lflag &^= unix.ECHO
  63. return tcset(fd, &newState)
  64. }
  65. func setRawTerminal(fd uintptr) (*State, error) {
  66. return makeRaw(fd)
  67. }
  68. func setRawTerminalOutput(fd uintptr) (*State, error) {
  69. return nil, nil
  70. }
  71. func tcget(fd uintptr) (*unix.Termios, error) {
  72. p, err := unix.IoctlGetTermios(int(fd), getTermios)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return p, nil
  77. }
  78. func tcset(fd uintptr, p *unix.Termios) error {
  79. return unix.IoctlSetTermios(int(fd), setTermios, p)
  80. }