~mna/sendkeys

ref: v0.1.0 sendkeys/sendkeys.go -rw-r--r-- 1.6 KiB
008be5a9Martin Angers add github mirror 2 years ago
                                                                                
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
// Package sendkeys simulates user input in a terminal.
package sendkeys

import (
	"os"
	"time"

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

// Target represents the tty to which the keys are sent. Create one by calling
// Open and send keys using Target.SendRunes or Target.SendBytes. The Target
// must be closed after use.
type Target struct {
	f *os.File
	d time.Duration
}

// Open returns a Target that sends keys to the specified TTY. The delay is the
// time to wait before sending each separate string when SendRunes or SendBytes
// is called.
func Open(ttyPath string, delay time.Duration) (*Target, error) {
	f, err := os.Open(ttyPath)
	if err != nil {
		return nil, err
	}
	return &Target{f: f, d: delay}, nil
}

// Close releases the resources used by the Target.
func (t *Target) Close() error {
	return t.f.Close()
}

// SendRunes sends each rune of each string the the Target. All runes of a
// given string are sent without delay, and the target's delay is applied
// between each string.
func (t *Target) SendRunes(strs ...string) (int, error) {
	var n int
	for _, str := range strs {
		for _, r := range str {
			if err := unix.IoctlSetPointerInt(int(t.f.Fd()), unix.TIOCSTI, int(r)); err != nil {
				return n, err
			}
			n++
		}
		time.Sleep(t.d)
	}
	return n, nil
}

// SendBytes is like SendRunes except it sends each byte separately, instead if
// each rune.
func (t *Target) SendBytes(strs ...string) (int, error) {
	var n int
	for _, str := range strs {
		for i := 0; i < len(str); i++ {
			v := int(str[i])
			if err := unix.IoctlSetPointerInt(int(t.f.Fd()), unix.TIOCSTI, v); err != nil {
				return n, err
			}
			n++
		}
		time.Sleep(t.d)
	}
	return n, nil
}