-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
capture.go
463 lines (412 loc) · 9.83 KB
/
capture.go
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package adb
import (
"context"
"encoding/json"
"errors"
"log"
"regexp"
"strconv"
"strings"
"time"
)
// CaptureSequence allows you to record a series of taps and swipes on the screen to replay later
//
// This function is useful if you need to run an obscure shell command or if
// you require functionality not provided by the exposed functions here.
// Instead of using Shell, please consider submitting a PR with the functionality
// you require.
type SeqType int
const (
SeqSwipe SeqType = iota
SeqTap
SeqSleep
)
type TapSequenceImporter struct {
Events []SequenceImporter
Resolution Resolution
}
type SequenceImporter struct {
Duration time.Duration
Type SeqType
X int
Y int
X1 int
Y1 int
X2 int
Y2 int
Start time.Time
End time.Time
}
func (si SequenceImporter) ToInput() Input {
switch si.Type {
case SeqSleep:
return SequenceSleep{Duration: si.Duration, Type: SeqSleep}
case SeqSwipe:
return SequenceSwipe{
X1: si.X1, Y1: si.Y1,
X2: si.X2, Y2: si.Y2,
Start: si.Start,
End: si.End, Type: SeqSwipe,
}
case SeqTap:
return SequenceTap{
X: si.X, Y: si.Y,
Start: si.Start,
End: si.End, Type: SeqTap,
}
default:
return SequenceSleep{Duration: time.Millisecond * 0, Type: SeqSleep}
}
}
type SequenceSleep struct {
Duration time.Duration
Type SeqType
}
func (s SequenceSleep) Play(d Device, ctx context.Context) error {
// TODO check if context is expired
time.Sleep(s.Duration)
return nil
}
func (s SequenceSleep) Length() time.Duration {
return s.Duration
}
func (s SequenceSleep) StartTime() time.Time {
return time.Time{}
}
func (s SequenceSleep) EndTime() time.Time {
return time.Time{}
}
type SequenceTap struct {
X int
Y int
Start time.Time
End time.Time
Type SeqType
}
func (s SequenceTap) Play(d Device, ctx context.Context) error {
return d.Tap(ctx, s.X, s.Y)
}
func (s SequenceTap) Length() time.Duration {
return 0
}
func (s SequenceTap) StartTime() time.Time {
return s.Start
}
func (s SequenceTap) EndTime() time.Time {
return s.End
}
type SequenceSwipe struct {
X1 int
Y1 int
X2 int
Y2 int
Start time.Time
End time.Time
Type SeqType
}
func (s SequenceSwipe) Play(d Device, ctx context.Context) error {
return d.Swipe(ctx, s.X1, s.Y1, s.X2, s.Y2, s.Length())
}
func (s SequenceSwipe) StartTime() time.Time {
return s.Start
}
func (s SequenceSwipe) EndTime() time.Time {
return s.End
}
func (s SequenceSwipe) Length() time.Duration {
return s.End.Sub(s.Start)
}
type Input interface {
Play(d Device, ctx context.Context) error
Length() time.Duration
StartTime() time.Time
EndTime() time.Time
}
type TapSequence struct {
Events []Input
Resolution Resolution
}
type Resolution struct {
Width int
Height int
}
func (t TapSequence) ToJSON() []byte {
b, _ := json.Marshal(t)
return b
}
func TapSequenceFromJSON(j []byte) (TapSequence, error) {
var ti TapSequenceImporter
var t TapSequence
err := json.Unmarshal(j, &ti)
if err != nil {
return t, err
}
t.Resolution = ti.Resolution
for _, ie := range ti.Events {
t.Events = append(t.Events, ie.ToInput())
}
return t, nil
}
// ShortenSleep allows you to shorten all the sleep times between tap and swipe events.
//
// Provide a scalar value to divide the sleeps by. Providing `2` will halve all
// sleep durations in the TapSequence. Swipe durations and tap durations are
// unaffected.
func (t TapSequence) ShortenSleep(scalar int) TapSequence {
seq := []Input{}
for _, s := range t.Events {
switch y := s.(type) {
case SequenceSleep:
y.Duration = y.Duration / time.Duration(scalar)
seq = append(seq, y)
default:
seq = append(seq, s)
}
}
t.Events = seq
return t
}
// GetLength returns the length of all Input events inside of a given TapSequence
//
// This function is useful for devermining how long a context timeout should
// last when calling ReplayTapSequence
func (t TapSequence) GetLength() time.Duration {
duration := time.Duration(0)
for _, x := range t.Events {
duration += x.Length()
}
return duration * 110 / 100
}
func (d Device) ReplayTapSequence(ctx context.Context, t TapSequence) error {
for _, e := range t.Events {
err := e.Play(d, ctx)
if err != nil {
return err
}
}
return nil
}
// CaptureSequence allows you to capture and replay screen taps and swipes.
//
// ctx, cancelFunc := context.WithCancel(context.TODO())
//
// go dev.CaptureSequence(ctx)
// time.Sleep(time.Second * 30)
// cancelFunc()
func (d Device) CaptureSequence(ctx context.Context) (t TapSequence, err error) {
t.Resolution, err = d.GetScreenResolution(ctx)
if err != nil {
return
}
// this command will never finish without ctx expiring. As a result,
// it will always return error code 130 if successful
stdout, _, errCode, err := execute(ctx, []string{"-s", string(d.SerialNo), "shell", "getevent", "-tl"})
// TODO better error checking here
if errors.Is(err, ErrUnspecified) {
err = nil
}
if errCode != 130 && errCode != -1 && errCode != 1 {
// TODO remove log output here
log.Printf("Expected error code 130 or -1, but got %d\n", errCode)
}
if stdout == "" {
return TapSequence{}, ErrStdoutEmpty
}
t.Events = parseGetEvent(stdout)
return
}
type event struct {
TimeStamp time.Time
DevicePath string
Type string
Key string
Value string
}
func (e event) isBTNTouch() bool {
return e.Key == "BTN_TOUCH"
}
func (e event) isEvABS() bool {
return e.Type == "EV_ABS"
}
func (e event) isPositionY() bool {
return e.isEvABS() && e.Key == "ABS_MT_POSITION_Y"
}
func (e event) isPositionX() bool {
return e.isEvABS() && e.Key == "ABS_MT_POSITION_X"
}
func (e event) isBTNUp() bool {
return e.isBTNTouch() && e.Value == "UP"
}
func (e event) isBTNDown() bool {
return e.isBTNTouch() && e.Value == "DOWN"
}
func (e event) GetNumeric() (int, error) {
i, err := strconv.ParseInt(e.Value, 16, 64)
if err != nil {
return 0, err
}
return int(i), nil
}
func parseGetEvent(input string) (events []Input) {
lines := strings.Split(input, "\n")
lines = trimDeviceDescriptors(lines)
touchEvents := parseInputToEvent(lines)
touches := getEventSlices(touchEvents)
events = touchesToInputs(touches)
events = insertSleeps(events)
return
}
func touchesToInputs(events []eventSet) []Input {
inputs := []Input{}
for _, eventSet := range events {
i, err := eventSet.ToInput()
if err == nil {
inputs = append(inputs, i)
}
}
return inputs
}
type eventSet []event
func insertSleeps(inputs []Input) []Input {
sleepingInputs := []Input{}
for i, input := range inputs {
if i != 0 {
prev := sleepingInputs[len(sleepingInputs)-1].EndTime()
curr := input.EndTime()
var sleep SequenceSleep
sleep.Duration = curr.Sub(prev)
sleep.Type = SeqSleep
sleepingInputs = append(sleepingInputs, sleep)
}
sleepingInputs = append(sleepingInputs, input)
}
return sleepingInputs
}
// trawls through the list of events in a set.
// the returned Input is always a swipe, as android can automatically
// decide to treat a swipe as a tap if necessary.
// taps are made available to the end user should they be manually set
// but it's safer to just use swipes as there's no chance of accidentally
// treating a swipe as a tap when guessing at the duration and distance
// between the touch down and pick up loci
func (e eventSet) ToInput() (Input, error) {
var (
swipe SequenceSwipe
startx, starty int64
xFound, yFound = false, false
endx, endy int64
)
var err error
for i := 0; i < len(e); i++ {
if xFound && yFound {
break
}
if e[i].isPositionX() {
xFound = true
startx, err = strconv.ParseInt(e[i].Value, 16, 64)
if err != nil {
return nil, err
}
}
if e[i].isPositionY() {
yFound = true
starty, err = strconv.ParseInt(e[i].Value, 16, 64)
if err != nil {
return nil, err
}
}
}
if !xFound || !yFound {
return nil, ErrCoordinatesNotFound
}
xFound, yFound = false, false
for i := len(e) - 1; i >= 0; i-- {
if xFound && yFound {
break
}
if e[i].isPositionX() {
xFound = true
endx, err = strconv.ParseInt(e[i].Value, 16, 64)
if err != nil {
return nil, err
}
}
if e[i].isPositionY() {
yFound = true
endy, err = strconv.ParseInt(e[i].Value, 16, 64)
if err != nil {
return nil, err
}
}
}
swipe.X1 = int(startx)
swipe.X2 = int(endx)
swipe.Y1 = int(starty)
swipe.Y2 = int(endy)
swipe.Start = e[0].TimeStamp
swipe.End = e[len(e)-1].TimeStamp
swipe.Type = SeqSwipe
return swipe, err
}
// Accepts a slice of events
// returns a slice of eventSets, where an eventSet is a group of events
// guaranteed to start with a DOWN event and end with an UP event,
// containing exactly one of each
func getEventSlices(events []event) []eventSet {
eventSets := []eventSet{{}}
current := 0
foundDown := false
for _, e := range events {
if !foundDown {
if e.isBTNDown() {
foundDown = true
} else {
continue
}
}
eventSets[current] = append(eventSets[current], e)
if e.isBTNUp() {
current++
foundDown = false
eventSets = append(eventSets, []event{})
}
}
eventSets = eventSets[:len(eventSets)-1]
return eventSets
}
func parseInputToEvent(input []string) []event {
var e []event
r := regexp.MustCompile(`\[\s*(\d+\.\d+)]\s*(.*):\s*(\w*)\s*(\w*)\s*(\w*)`)
for _, line := range input {
var l event
timeStr := r.FindStringSubmatch(line)
if len(timeStr) != 6 {
continue
}
f, err := strconv.ParseFloat(timeStr[1], 32)
if err != nil {
continue
}
msec := int64(f * 1000)
l.TimeStamp = time.UnixMilli(msec)
l.DevicePath = timeStr[2]
l.Type = timeStr[3]
l.Key = timeStr[4]
l.Value = timeStr[5]
e = append(e, l)
}
return e
}
func trimDeviceDescriptors(input []string) []string {
start := 0
for i, line := range input {
if strings.Contains(line, "DOWN") {
start = i
break
}
}
for i := range input {
input[i] = strings.TrimSpace(input[i])
}
return input[start : len(input)-1]
}