vendor/github.com/go-rod/rod/input.go

457 lines · 10463 bytes

  1package rod
  2
  3import (
  4	"fmt"
  5	"sync"
  6
  7	"github.com/go-rod/rod/lib/input"
  8	"github.com/go-rod/rod/lib/proto"
  9	"github.com/go-rod/rod/lib/utils"
 10	"github.com/ysmood/gson"
 11)
 12
 13// Keyboard represents the keyboard on a page, it's always related the main frame.
 14type Keyboard struct {
 15	sync.Mutex
 16
 17	page *Page
 18
 19	// pressed keys must be released before it can be pressed again
 20	pressed map[input.Key]struct{}
 21}
 22
 23func (p *Page) newKeyboard() *Page {
 24	p.Keyboard = &Keyboard{page: p, pressed: map[input.Key]struct{}{}}
 25	return p
 26}
 27
 28func (k *Keyboard) getModifiers() int {
 29	k.Lock()
 30	defer k.Unlock()
 31	return k.modifiers()
 32}
 33
 34func (k *Keyboard) modifiers() int {
 35	ms := 0
 36	for key := range k.pressed {
 37		ms |= key.Modifier()
 38	}
 39	return ms
 40}
 41
 42// Press the key down.
 43// To input characters that are not on the keyboard, such as Chinese or Japanese, you should
 44// use method like [Page.InsertText].
 45func (k *Keyboard) Press(key input.Key) error {
 46	defer k.page.tryTrace(TraceTypeInput, "press key: "+key.Info().Code)()
 47	k.page.browser.trySlowMotion()
 48
 49	k.Lock()
 50	defer k.Unlock()
 51
 52	k.pressed[key] = struct{}{}
 53
 54	return key.Encode(proto.InputDispatchKeyEventTypeKeyDown, k.modifiers()).Call(k.page)
 55}
 56
 57// Release the key.
 58func (k *Keyboard) Release(key input.Key) error {
 59	defer k.page.tryTrace(TraceTypeInput, "release key: "+key.Info().Code)()
 60
 61	k.Lock()
 62	defer k.Unlock()
 63
 64	if _, has := k.pressed[key]; !has {
 65		return nil
 66	}
 67
 68	delete(k.pressed, key)
 69
 70	return key.Encode(proto.InputDispatchKeyEventTypeKeyUp, k.modifiers()).Call(k.page)
 71}
 72
 73// Type releases the key after the press.
 74func (k *Keyboard) Type(keys ...input.Key) (err error) {
 75	for _, key := range keys {
 76		err = k.Press(key)
 77		if err != nil {
 78			return
 79		}
 80		err = k.Release(key)
 81		if err != nil {
 82			return
 83		}
 84	}
 85	return
 86}
 87
 88// KeyActionType enum.
 89type KeyActionType int
 90
 91// KeyActionTypes.
 92const (
 93	KeyActionPress KeyActionType = iota
 94	KeyActionRelease
 95	KeyActionTypeKey
 96)
 97
 98// KeyAction to perform.
 99type KeyAction struct {
100	Type KeyActionType
101	Key  input.Key
102}
103
104// KeyActions to simulate.
105type KeyActions struct {
106	keyboard *Keyboard
107
108	Actions []KeyAction
109}
110
111// KeyActions simulates the type actions on a physical keyboard.
112// Useful when input shortcuts like ctrl+enter .
113func (p *Page) KeyActions() *KeyActions {
114	return &KeyActions{keyboard: p.Keyboard}
115}
116
117// Press keys is guaranteed to have a release at the end of actions.
118func (ka *KeyActions) Press(keys ...input.Key) *KeyActions {
119	for _, key := range keys {
120		ka.Actions = append(ka.Actions, KeyAction{KeyActionPress, key})
121	}
122	return ka
123}
124
125// Release keys.
126func (ka *KeyActions) Release(keys ...input.Key) *KeyActions {
127	for _, key := range keys {
128		ka.Actions = append(ka.Actions, KeyAction{KeyActionRelease, key})
129	}
130	return ka
131}
132
133// Type will release the key immediately after the pressing.
134func (ka *KeyActions) Type(keys ...input.Key) *KeyActions {
135	for _, key := range keys {
136		ka.Actions = append(ka.Actions, KeyAction{KeyActionTypeKey, key})
137	}
138	return ka
139}
140
141// Do the actions.
142func (ka *KeyActions) Do() (err error) {
143	for _, a := range ka.balance() {
144		switch a.Type {
145		case KeyActionPress:
146			err = ka.keyboard.Press(a.Key)
147		case KeyActionRelease:
148			err = ka.keyboard.Release(a.Key)
149		case KeyActionTypeKey:
150			err = ka.keyboard.Type(a.Key)
151		}
152		if err != nil {
153			return
154		}
155	}
156	return
157}
158
159// Make sure there's at least one release after the presses, such as:
160//
161//	p1,p2,p1,r1 => p1,p2,p1,r1,r2
162func (ka *KeyActions) balance() []KeyAction {
163	actions := ka.Actions
164
165	h := map[input.Key]bool{}
166	for _, a := range actions {
167		switch a.Type {
168		case KeyActionPress:
169			h[a.Key] = true
170		case KeyActionRelease, KeyActionTypeKey:
171			h[a.Key] = false
172		}
173	}
174
175	for key, needRelease := range h {
176		if needRelease {
177			actions = append(actions, KeyAction{KeyActionRelease, key})
178		}
179	}
180
181	return actions
182}
183
184// InsertText is like pasting text into the page.
185func (p *Page) InsertText(text string) error {
186	defer p.tryTrace(TraceTypeInput, "insert text "+text)()
187	p.browser.trySlowMotion()
188
189	err := proto.InputInsertText{Text: text}.Call(p)
190	return err
191}
192
193// Mouse represents the mouse on a page, it's always related the main frame.
194type Mouse struct {
195	sync.Mutex
196
197	page *Page
198
199	id string // mouse svg dom element id
200
201	pos proto.Point
202
203	// the buttons is currently being pressed, reflects the press order
204	buttons []proto.InputMouseButton
205}
206
207func (p *Page) newMouse() *Page {
208	p.Mouse = &Mouse{page: p, id: utils.RandString(8)}
209	return p
210}
211
212// Position of current cursor.
213func (m *Mouse) Position() proto.Point {
214	m.Lock()
215	defer m.Unlock()
216	return m.pos
217}
218
219// MoveTo the absolute position.
220func (m *Mouse) MoveTo(p proto.Point) error {
221	m.Lock()
222	defer m.Unlock()
223
224	button, buttons := input.EncodeMouseButton(m.buttons)
225
226	m.page.browser.trySlowMotion()
227
228	err := proto.InputDispatchMouseEvent{
229		Type:      proto.InputDispatchMouseEventTypeMouseMoved,
230		X:         p.X,
231		Y:         p.Y,
232		Button:    button,
233		Buttons:   gson.Int(buttons),
234		Modifiers: m.page.Keyboard.getModifiers(),
235	}.Call(m.page)
236	if err != nil {
237		return err
238	}
239
240	// to make sure set only when call is successful
241	m.pos = p
242
243	if m.page.browser.trace {
244		if !m.updateMouseTracer() {
245			m.initMouseTracer()
246			m.updateMouseTracer()
247		}
248	}
249
250	return nil
251}
252
253// MoveAlong the guide function.
254// Every time the guide function is called it should return the next mouse position, return true to stop.
255// Read the source code of [Mouse.MoveLinear] as an example to use this method.
256func (m *Mouse) MoveAlong(guide func() (proto.Point, bool)) error {
257	for {
258		p, stop := guide()
259		if stop {
260			return m.MoveTo(p)
261		}
262
263		err := m.MoveTo(p)
264		if err != nil {
265			return err
266		}
267	}
268}
269
270// MoveLinear to the absolute position with the given steps.
271// Such as move from (0,0) to (6,6) with 3 steps, the mouse will first move to (2,2) then (4,4) then (6,6).
272func (m *Mouse) MoveLinear(to proto.Point, steps int) error {
273	p := m.Position()
274	step := to.Minus(p).Scale(1 / float64(steps))
275	count := 0
276
277	return m.MoveAlong(func() (proto.Point, bool) {
278		count++
279		if count == steps {
280			return to, true
281		}
282
283		p = p.Add(step)
284		return p, false
285	})
286}
287
288// Scroll the relative offset with specified steps.
289func (m *Mouse) Scroll(offsetX, offsetY float64, steps int) error {
290	m.Lock()
291	defer m.Unlock()
292
293	defer m.page.tryTrace(TraceTypeInput, fmt.Sprintf("scroll (%.2f, %.2f)", offsetX, offsetY))()
294	m.page.browser.trySlowMotion()
295
296	if steps < 1 {
297		steps = 1
298	}
299
300	button, buttons := input.EncodeMouseButton(m.buttons)
301
302	stepX := offsetX / float64(steps)
303	stepY := offsetY / float64(steps)
304
305	for i := 0; i < steps; i++ {
306		err := proto.InputDispatchMouseEvent{
307			Type:      proto.InputDispatchMouseEventTypeMouseWheel,
308			Button:    button,
309			Buttons:   gson.Int(buttons),
310			Modifiers: m.page.Keyboard.getModifiers(),
311			DeltaX:    stepX,
312			DeltaY:    stepY,
313			X:         m.pos.X,
314			Y:         m.pos.Y,
315		}.Call(m.page)
316		if err != nil {
317			return err
318		}
319	}
320
321	return nil
322}
323
324// Down holds the button down.
325func (m *Mouse) Down(button proto.InputMouseButton, clickCount int) error {
326	m.Lock()
327	defer m.Unlock()
328
329	toButtons := append(append([]proto.InputMouseButton{}, m.buttons...), button)
330
331	_, buttons := input.EncodeMouseButton(toButtons)
332
333	err := proto.InputDispatchMouseEvent{
334		Type:       proto.InputDispatchMouseEventTypeMousePressed,
335		Button:     button,
336		Buttons:    gson.Int(buttons),
337		ClickCount: clickCount,
338		Modifiers:  m.page.Keyboard.getModifiers(),
339		X:          m.pos.X,
340		Y:          m.pos.Y,
341	}.Call(m.page)
342	if err != nil {
343		return err
344	}
345	m.buttons = toButtons
346	return nil
347}
348
349// Up releases the button.
350func (m *Mouse) Up(button proto.InputMouseButton, clickCount int) error {
351	m.Lock()
352	defer m.Unlock()
353
354	toButtons := []proto.InputMouseButton{}
355	for _, btn := range m.buttons {
356		if btn == button {
357			continue
358		}
359		toButtons = append(toButtons, btn)
360	}
361
362	_, buttons := input.EncodeMouseButton(toButtons)
363
364	err := proto.InputDispatchMouseEvent{
365		Type:       proto.InputDispatchMouseEventTypeMouseReleased,
366		Button:     button,
367		Buttons:    gson.Int(buttons),
368		ClickCount: clickCount,
369		Modifiers:  m.page.Keyboard.getModifiers(),
370		X:          m.pos.X,
371		Y:          m.pos.Y,
372	}.Call(m.page)
373	if err != nil {
374		return err
375	}
376	m.buttons = toButtons
377	return nil
378}
379
380// Click the button. It's the combination of [Mouse.Down] and [Mouse.Up].
381func (m *Mouse) Click(button proto.InputMouseButton, clickCount int) error {
382	m.page.browser.trySlowMotion()
383
384	err := m.Down(button, clickCount)
385	if err != nil {
386		return err
387	}
388
389	return m.Up(button, clickCount)
390}
391
392// Touch presents a touch device, such as a hand with fingers, each finger is a [proto.InputTouchPoint].
393// Touch events is stateless, we use the struct here only as a namespace to make the API style unified.
394type Touch struct {
395	page *Page
396}
397
398func (p *Page) newTouch() *Page {
399	p.Touch = &Touch{page: p}
400	return p
401}
402
403// Start a touch action.
404func (t *Touch) Start(points ...*proto.InputTouchPoint) error {
405	// TODO: https://crbug.com/613219
406	_ = t.page.WaitRepaint()
407	_ = t.page.WaitRepaint()
408
409	return proto.InputDispatchTouchEvent{
410		Type:        proto.InputDispatchTouchEventTypeTouchStart,
411		TouchPoints: points,
412		Modifiers:   t.page.Keyboard.getModifiers(),
413	}.Call(t.page)
414}
415
416// Move touch points. Use the [proto.InputTouchPoint.ID] (Touch.identifier) to track points.
417// Doc: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
418func (t *Touch) Move(points ...*proto.InputTouchPoint) error {
419	return proto.InputDispatchTouchEvent{
420		Type:        proto.InputDispatchTouchEventTypeTouchMove,
421		TouchPoints: points,
422		Modifiers:   t.page.Keyboard.getModifiers(),
423	}.Call(t.page)
424}
425
426// End touch action.
427func (t *Touch) End() error {
428	return proto.InputDispatchTouchEvent{
429		Type:        proto.InputDispatchTouchEventTypeTouchEnd,
430		TouchPoints: []*proto.InputTouchPoint{},
431		Modifiers:   t.page.Keyboard.getModifiers(),
432	}.Call(t.page)
433}
434
435// Cancel touch action.
436func (t *Touch) Cancel() error {
437	return proto.InputDispatchTouchEvent{
438		Type:        proto.InputDispatchTouchEventTypeTouchCancel,
439		TouchPoints: []*proto.InputTouchPoint{},
440		Modifiers:   t.page.Keyboard.getModifiers(),
441	}.Call(t.page)
442}
443
444// Tap dispatches a touchstart and touchend event.
445func (t *Touch) Tap(x, y float64) error {
446	defer t.page.tryTrace(TraceTypeInput, "touch")()
447	t.page.browser.trySlowMotion()
448
449	p := &proto.InputTouchPoint{X: x, Y: y}
450
451	err := t.Start(p)
452	if err != nil {
453		return err
454	}
455
456	return t.End()
457}