vendor/github.com/go-rod/rod/lib/input/keyboard.go
138 lines · 2788 bytes
1// Package input ...
2package input
3
4import (
5 "github.com/go-rod/rod/lib/proto"
6 "github.com/ysmood/gson"
7)
8
9// Modifier values.
10const (
11 ModifierAlt = 1
12 ModifierControl = 2
13 ModifierMeta = 4
14 ModifierShift = 8
15)
16
17// Key symbol.
18type Key rune
19
20// keyMap for key description.
21var keyMap = map[Key]KeyInfo{}
22
23// keyMapShifted for shifted key description.
24var keyMapShifted = map[Key]KeyInfo{}
25
26var keyShiftedMap = map[Key]Key{}
27
28// AddKey to KeyMap.
29func AddKey(key string, shiftedKey string, code string, keyCode int, location int) Key {
30 if len(key) == 1 {
31 r := Key(key[0])
32 if _, has := keyMap[r]; !has {
33 keyMap[r] = KeyInfo{key, code, keyCode, location}
34
35 if len(shiftedKey) == 1 {
36 rs := Key(shiftedKey[0])
37 keyMapShifted[rs] = KeyInfo{shiftedKey, code, keyCode, location}
38 keyShiftedMap[r] = rs
39 }
40 return r
41 }
42 }
43
44 k := Key(keyCode + (location+1)*256)
45 keyMap[k] = KeyInfo{key, code, keyCode, location}
46
47 return k
48}
49
50// Info of the key.
51func (k Key) Info() KeyInfo {
52 if k, has := keyMap[k]; has {
53 return k
54 }
55 if k, has := keyMapShifted[k]; has {
56 return k
57 }
58
59 panic("key not defined")
60}
61
62// KeyInfo of a key
63// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
64type KeyInfo struct {
65 // Here's the value for Shift key on the keyboard
66
67 Key string // Shift
68 Code string // ShiftLeft
69 KeyCode int // 16
70 Location int // 1
71}
72
73// Shift returns the shifted key, such as shifted "1" is "!".
74func (k Key) Shift() (Key, bool) {
75 s, has := keyShiftedMap[k]
76 return s, has
77}
78
79// Printable returns true if the key is printable.
80func (k Key) Printable() bool {
81 return len(k.Info().Key) == 1
82}
83
84// Modifier returns the modifier value of the key.
85func (k Key) Modifier() int {
86 switch k.Info().KeyCode {
87 case 18:
88 return ModifierAlt
89 case 17:
90 return ModifierControl
91 case 91, 92:
92 return ModifierMeta
93 case 16:
94 return ModifierShift
95 }
96 return 0
97}
98
99// Encode general key event.
100func (k Key) Encode(t proto.InputDispatchKeyEventType, modifiers int) *proto.InputDispatchKeyEvent {
101 tp := t
102 if t == proto.InputDispatchKeyEventTypeKeyDown && !k.Printable() {
103 tp = proto.InputDispatchKeyEventTypeRawKeyDown
104 }
105
106 info := k.Info()
107 l := gson.Int(info.Location)
108 keypad := false
109 if info.Location == 3 {
110 l = nil
111 keypad = true
112 }
113
114 txt := ""
115 if k.Printable() {
116 txt = info.Key
117 }
118
119 var cmd []string
120 if IsMac {
121 cmd = macCommands[info.Key]
122 }
123
124 e := &proto.InputDispatchKeyEvent{
125 Type: tp,
126 WindowsVirtualKeyCode: info.KeyCode,
127 Code: info.Code,
128 Key: info.Key,
129 Text: txt,
130 UnmodifiedText: txt,
131 Location: l,
132 IsKeypad: keypad,
133 Modifiers: modifiers,
134 Commands: cmd,
135 }
136
137 return e
138}