summaryrefslogtreecommitdiff
path: root/vendor/gopkg.in/cheggaaa/pb.v1/pb_x.go
blob: af42517604b4bf64fb478a288ae41be92b6a6510 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// +build linux darwin freebsd netbsd openbsd solaris dragonfly
// +build !appengine !js

package pb

import (
	"errors"
	"fmt"
	"os"
	"os/signal"
	"sync"
	"syscall"

	"golang.org/x/sys/unix"
)

var ErrPoolWasStarted = errors.New("Bar pool was started")

var (
	echoLockMutex    sync.Mutex
	origTermStatePtr *unix.Termios
	tty              *os.File
	istty            bool
)

func init() {
	echoLockMutex.Lock()
	defer echoLockMutex.Unlock()

	var err error
	tty, err = os.Open("/dev/tty")
	istty = true
	if err != nil {
		tty = os.Stdin
		istty = false
	}
}

// terminalWidth returns width of the terminal.
func terminalWidth() (int, error) {
	if !istty {
		return 0, errors.New("Not Supported")
	}
	echoLockMutex.Lock()
	defer echoLockMutex.Unlock()

	fd := int(tty.Fd())

	ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
	if err != nil {
		return 0, err
	}

	return int(ws.Col), nil
}

func lockEcho() (shutdownCh chan struct{}, err error) {
	echoLockMutex.Lock()
	defer echoLockMutex.Unlock()
	if istty {
		if origTermStatePtr != nil {
			return shutdownCh, ErrPoolWasStarted
		}

		fd := int(tty.Fd())

		origTermStatePtr, err = unix.IoctlGetTermios(fd, ioctlReadTermios)
		if err != nil {
			return nil, fmt.Errorf("Can't get terminal settings: %v", err)
		}

		oldTermios := *origTermStatePtr
		newTermios := oldTermios
		newTermios.Lflag &^= syscall.ECHO
		newTermios.Lflag |= syscall.ICANON | syscall.ISIG
		newTermios.Iflag |= syscall.ICRNL
		if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, &newTermios); err != nil {
			return nil, fmt.Errorf("Can't set terminal settings: %v", err)
		}

	}
	shutdownCh = make(chan struct{})
	go catchTerminate(shutdownCh)
	return
}

func unlockEcho() error {
	echoLockMutex.Lock()
	defer echoLockMutex.Unlock()
	if istty {
		if origTermStatePtr == nil {
			return nil
		}

		fd := int(tty.Fd())

		if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, origTermStatePtr); err != nil {
			return fmt.Errorf("Can't set terminal settings: %v", err)
		}

	}
	origTermStatePtr = nil

	return nil
}

// listen exit signals and restore terminal state
func catchTerminate(shutdownCh chan struct{}) {
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL)
	defer signal.Stop(sig)
	select {
	case <-shutdownCh:
		unlockEcho()
	case <-sig:
		unlockEcho()
	}
}