-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathandroid.go
More file actions
1350 lines (1128 loc) · 37.6 KB
/
android.go
File metadata and controls
1350 lines (1128 loc) · 37.6 KB
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package devices
import (
"context"
"encoding/base64"
"encoding/xml"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/mobile-next/mobilecli/devices/wda"
"github.com/mobile-next/mobilecli/types"
"github.com/mobile-next/mobilecli/utils"
)
// AndroidDevice implements the ControllableDevice interface for Android devices
type AndroidDevice struct {
id string
name string
version string
state string // "online" or "offline"
transportID string // adb transport ID (e.g., "emulator-5554"), only set for online devices
model string
}
func (d *AndroidDevice) ID() string {
return d.id
}
func (d *AndroidDevice) Name() string {
return d.name
}
func (d *AndroidDevice) Version() string {
return d.version
}
func (d *AndroidDevice) Platform() string {
return "android"
}
func (d *AndroidDevice) DeviceType() string {
// check transportID for online devices, or state for offline
if strings.HasPrefix(d.transportID, "emulator-") || d.state == "offline" {
return "emulator"
} else {
return "real"
}
}
func (d *AndroidDevice) State() string {
return d.state
}
func getAndroidSdkPath() string {
sdkPath := os.Getenv("ANDROID_HOME")
if sdkPath != "" {
if _, err := os.Stat(sdkPath); err == nil {
return sdkPath
}
}
// try default Android SDK location on macOS
homeDir := os.Getenv("HOME")
if homeDir != "" {
defaultPath := filepath.Join(homeDir, "Library", "Android", "sdk")
if _, err := os.Stat(defaultPath); err == nil {
return defaultPath
}
}
// try default Android SDK location on Windows
if runtime.GOOS == "windows" {
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData != "" {
defaultPath := filepath.Join(localAppData, "Android", "Sdk")
if _, err := os.Stat(defaultPath); err == nil {
return defaultPath
}
}
// fallback to USERPROFILE on Windows
userProfile := os.Getenv("USERPROFILE")
if userProfile != "" {
defaultPath := filepath.Join(userProfile, "AppData", "Local", "Android", "Sdk")
if _, err := os.Stat(defaultPath); err == nil {
return defaultPath
}
}
}
return ""
}
func getAdbPath() string {
sdkPath := getAndroidSdkPath()
if sdkPath != "" {
adbPath := filepath.Join(sdkPath, "platform-tools", "adb")
if runtime.GOOS == "windows" {
adbPath += ".exe"
}
return adbPath
}
// best effort, look in path
return "adb"
}
func getEmulatorPath() string {
sdkPath := getAndroidSdkPath()
if sdkPath != "" {
emulatorPath := filepath.Join(sdkPath, "emulator", "emulator")
if runtime.GOOS == "windows" {
emulatorPath += ".exe"
}
if _, err := os.Stat(emulatorPath); err == nil {
return emulatorPath
}
}
// best effort, look in path
return "emulator"
}
// getAdbIdentifier returns the correct device identifier for adb commands
// uses transportID for online devices (e.g., "emulator-5554"), or id for offline
func (d *AndroidDevice) getAdbIdentifier() string {
if d.transportID != "" {
return d.transportID
}
return d.id
}
func (d *AndroidDevice) runAdbCommand(args ...string) ([]byte, error) {
deviceID := d.getAdbIdentifier()
cmdArgs := append([]string{"-s", deviceID}, args...)
cmd := exec.Command(getAdbPath(), cmdArgs...)
return cmd.CombinedOutput()
}
// getDisplayCount counts the number of displays on the device
func (d *AndroidDevice) getDisplayCount() int {
output, err := d.runAdbCommand("shell", "dumpsys", "SurfaceFlinger", "--display-id")
if err != nil {
return 1 // assume single display on error
}
count := 0
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "Display ") {
count++
}
}
return count
}
// parseDisplayIdFromCmdDisplay extracts display ID from "cmd display get-displays" output (Android 11+)
func parseDisplayIdFromCmdDisplay(output string) string {
lines := strings.Split(output, "\n")
for _, line := range lines {
// look for lines like "Display id X, ... state ON, ... uniqueId "..."
if strings.HasPrefix(line, "Display id ") &&
strings.Contains(line, ", state ON,") &&
strings.Contains(line, ", uniqueId ") {
re := regexp.MustCompile(`uniqueId "([^"]+)"`)
matches := re.FindStringSubmatch(line)
if len(matches) == 2 {
return strings.TrimPrefix(matches[1], "local:")
}
}
}
return ""
}
// parseDisplayIdFromDumpsysViewport extracts display ID from dumpsys DisplayViewport entries
func parseDisplayIdFromDumpsysViewport(dumpsys string) string {
re := regexp.MustCompile(`DisplayViewport\{type=INTERNAL[^}]*isActive=true[^}]*uniqueId='([^']+)'`)
matches := re.FindStringSubmatch(dumpsys)
if len(matches) == 2 {
return strings.TrimPrefix(matches[1], "local:")
}
return ""
}
// parseDisplayIdFromDumpsysState extracts display ID from dumpsys display state entries
func parseDisplayIdFromDumpsysState(dumpsys string) string {
re := regexp.MustCompile(`Display Id=(\d+)[\s\S]*?Display State=ON`)
matches := re.FindStringSubmatch(dumpsys)
if len(matches) == 2 {
return matches[1]
}
return ""
}
// getFirstDisplayId finds the first active display's unique ID
func (d *AndroidDevice) getFirstDisplayId() string {
// try using cmd display get-displays (Android 11+)
output, err := d.runAdbCommand("shell", "cmd", "display", "get-displays")
if err == nil {
if id := parseDisplayIdFromCmdDisplay(string(output)); id != "" {
return id
}
}
// fallback: parse dumpsys display for display info (compatible with older Android versions)
output, err = d.runAdbCommand("shell", "dumpsys", "display")
if err != nil {
return ""
}
dumpsys := string(output)
// try DisplayViewport entries with isActive=true and type=INTERNAL
if id := parseDisplayIdFromDumpsysViewport(dumpsys); id != "" {
return id
}
// final fallback: look for active display with state ON
return parseDisplayIdFromDumpsysState(dumpsys)
}
// captureScreenshot captures screenshot with optional display ID
func (d *AndroidDevice) captureScreenshot(displayID string) ([]byte, error) {
args := []string{"exec-out", "screencap", "-p"}
if displayID != "" {
args = append(args, "-d", displayID)
}
byteData, err := d.runAdbCommand(args...)
if err != nil {
return nil, fmt.Errorf("failed to take screenshot: %w", err)
}
return byteData, nil
}
func (d *AndroidDevice) TakeScreenshot() ([]byte, error) {
displayCount := d.getDisplayCount()
if displayCount <= 1 {
// backward compatibility for android 10 and below, and for single display devices
return d.captureScreenshot("")
}
// find the first display that is turned on, and capture that one
displayID := d.getFirstDisplayId()
if displayID == "" {
// no idea why, but we have displayCount >= 2, yet we failed to parse
// let's go with screencap's defaults and hope for the best
return d.captureScreenshot("")
}
return d.captureScreenshot(displayID)
}
// validLocaleTag checks that a locale tag only contains safe BCP 47 characters
var validLocaleTag = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$`)
func (d *AndroidDevice) LaunchApp(bundleID string, locales []string) error {
if len(locales) > 0 {
for _, l := range locales {
if !validLocaleTag.MatchString(l) {
return fmt.Errorf("invalid locale tag: %q", l)
}
}
localeArg := strings.Join(locales, ",")
output, err := d.runAdbCommand("shell", "cmd", "locale", "set-app-locales", bundleID, "--locales", localeArg)
if err != nil {
return fmt.Errorf("failed to set app locales for %s: %v\nOutput: %s", bundleID, err, string(output))
}
}
output, err := d.runAdbCommand("shell", "monkey", "-p", bundleID, "-c", "android.intent.category.LAUNCHER", "1")
if err != nil {
return fmt.Errorf("failed to launch app %s: %v\nOutput: %s", bundleID, err, string(output))
}
return nil
}
func (d *AndroidDevice) TerminateApp(bundleID string) error {
output, err := d.runAdbCommand("shell", "am", "force-stop", bundleID)
if err != nil {
return fmt.Errorf("failed to terminate app %s: %v\nOutput: %s", bundleID, err, string(output))
}
return nil
}
// Reboot reboots the Android device/emulator using `adb reboot`.
func (d *AndroidDevice) Reboot() error {
_, err := d.runAdbCommand("reboot")
if err != nil {
return err
}
return nil
}
// Shutdown shuts down the Android emulator
func (d *AndroidDevice) Shutdown() error {
if d.DeviceType() != "emulator" {
return fmt.Errorf("shutdown is only supported for emulators")
}
if d.state == "offline" {
return fmt.Errorf("emulator is already offline")
}
// use emu kill command for graceful shutdown
_, err := d.runAdbCommand("emu", "kill")
if err != nil {
return fmt.Errorf("failed to shutdown emulator: %w", err)
}
d.state = "offline"
d.transportID = ""
return nil
}
// Tap simulates a tap at (x, y) on the Android device.
func (d *AndroidDevice) Tap(x, y int) error {
_, err := d.runAdbCommand("shell", "input", "tap", fmt.Sprintf("%d", x), fmt.Sprintf("%d", y))
if err != nil {
return err
}
return nil
}
// LongPress simulates a long press at (x, y) on the Android device.
func (d *AndroidDevice) LongPress(x, y, duration int) error {
_, err := d.runAdbCommand("shell", "input", "swipe", fmt.Sprintf("%d", x), fmt.Sprintf("%d", y), fmt.Sprintf("%d", x), fmt.Sprintf("%d", y), fmt.Sprintf("%d", duration))
if err != nil {
return err
}
return nil
}
// Swipe simulates a swipe gesture from (x1, y1) to (x2, y2) on the Android device with 1000ms duration.
func (d *AndroidDevice) Swipe(x1, y1, x2, y2 int) error {
_, err := d.runAdbCommand("shell", "input", "swipe", fmt.Sprintf("%d", x1), fmt.Sprintf("%d", y1), fmt.Sprintf("%d", x2), fmt.Sprintf("%d", y2), "1000")
if err != nil {
return err
}
return nil
}
// Gesture performs a sequence of touch actions on the Android device
func (d *AndroidDevice) Gesture(actions []wda.TapAction) error {
x := 0
y := 0
for _, action := range actions {
var cmd []string
if action.Type == "pause" {
time.Sleep(time.Duration(action.Duration) * time.Millisecond)
continue
}
switch action.Type {
case "pointerDown":
cmd = []string{"shell", "input", "touchscreen", "motionevent", "down", fmt.Sprintf("%d", x), fmt.Sprintf("%d", y)}
case "pointerMove":
x = action.X
y = action.Y
cmd = []string{"shell", "input", "touchscreen", "motionevent", "move", fmt.Sprintf("%d", action.X), fmt.Sprintf("%d", action.Y)}
case "pointerUp":
cmd = []string{"shell", "input", "touchscreen", "motionevent", "up", fmt.Sprintf("%d", x), fmt.Sprintf("%d", y)}
default:
return fmt.Errorf("unsupported gesture action type: %s", action.Type)
}
_, err := d.runAdbCommand(cmd...)
if err != nil {
return fmt.Errorf("failed to execute gesture action %s: %v", action.Type, err)
}
}
return nil
}
func parseAdbDevicesOutput(output string) []ControllableDevice {
var devices []ControllableDevice
lines := strings.Split(output, "\n")
for i := 1; i < len(lines); i++ {
line := strings.TrimSpace(lines[i])
parts := strings.Fields(line)
if len(parts) == 2 {
transportID := parts[0]
status := parts[1]
if status == "device" {
deviceID := transportID
// for emulators, use AVD name as the consistent ID
if strings.HasPrefix(transportID, "emulator-") {
avdName := getAVDName(transportID)
if avdName != "" {
deviceID = avdName
}
}
devices = append(devices, &AndroidDevice{
id: deviceID,
transportID: transportID,
name: getAndroidDeviceName(transportID),
version: getAndroidDeviceVersion(transportID),
state: "online",
model: getAndroidDeviceModel(transportID),
})
}
}
}
return devices
}
// getAVDName returns the AVD name for an emulator, or empty string if not an emulator
func getAVDName(transportID string) string {
avdCmd := exec.Command(getAdbPath(), "-s", transportID, "shell", "getprop", "ro.boot.qemu.avd_name")
avdOutput, err := avdCmd.CombinedOutput()
if err == nil && len(avdOutput) > 0 {
avdName := strings.TrimSpace(string(avdOutput))
return avdName
}
return ""
}
func getAndroidDeviceName(deviceID string) string {
// for emulators, prioritize AVD name
if strings.HasPrefix(deviceID, "emulator-") {
avdName := getAVDName(deviceID)
if avdName != "" {
return strings.ReplaceAll(avdName, "_", " ")
}
}
// for real devices, try getting device name from settings
nameCmd := exec.Command(getAdbPath(), "-s", deviceID, "shell", "settings", "get", "global", "device_name")
nameOutput, err := nameCmd.CombinedOutput()
if err == nil && len(nameOutput) > 0 {
name := strings.TrimSpace(string(nameOutput))
// settings returns "null" if the value is not set
if name != "" && name != "null" {
return name
}
}
// fall back to product model
modelCmd := exec.Command(getAdbPath(), "-s", deviceID, "shell", "getprop", "ro.product.model")
modelOutput, err := modelCmd.CombinedOutput()
if err == nil && len(modelOutput) > 0 {
return strings.TrimSpace(string(modelOutput))
}
return deviceID
}
func getAndroidDeviceModel(deviceID string) string {
modelCmd := exec.Command(getAdbPath(), "-s", deviceID, "shell", "getprop", "ro.product.model")
modelOutput, err := modelCmd.CombinedOutput()
if err == nil && len(modelOutput) > 0 {
return strings.TrimSpace(string(modelOutput))
}
return ""
}
func getAndroidDeviceVersion(deviceID string) string {
versionCmd := exec.Command(getAdbPath(), "-s", deviceID, "shell", "getprop", "ro.build.version.release")
versionOutput, err := versionCmd.CombinedOutput()
if err == nil && len(versionOutput) > 0 {
return strings.TrimSpace(string(versionOutput))
}
return ""
}
// GetAndroidDevices retrieves a list of connected Android devices
func GetAndroidDevices() ([]ControllableDevice, error) {
command := exec.Command(getAdbPath(), "devices")
output, err := command.CombinedOutput()
if err != nil {
status := command.ProcessState.ExitCode()
if status < 0 {
utils.Verbose("Failed running 'adb devices', is ANDROID_HOME set correctly?")
return []ControllableDevice{}, nil
}
return nil, fmt.Errorf("failed to run 'adb devices': %v", err)
}
androidDevices := parseAdbDevicesOutput(string(output))
return androidDevices, nil
}
func (d *AndroidDevice) StartAgent(config StartAgentConfig) error {
// if device is offline, return error - user should use 'device boot' command
if d.state == "offline" {
return fmt.Errorf("device is offline, use 'mobilecli device boot --device %s' to start the emulator", d.id)
}
// android doesn't need an agent to be started for online devices
return nil
}
// matchesAVDName checks if a device name matches an AVD name (pure function)
func matchesAVDName(avdName, deviceName string) bool {
normalizedAVD := strings.ReplaceAll(avdName, "_", " ")
return normalizedAVD == deviceName || avdName == deviceName
}
// waitForEmulatorBootComplete waits for an emulator to appear and be fully booted
func (d *AndroidDevice) waitForEmulatorBootComplete(ctx context.Context, avdName string) (string, error) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return "", fmt.Errorf("emulator boot cancelled: %w", ctx.Err())
case <-ticker.C:
// check if emulator is in device list
devices, err := GetAndroidDevices()
if err != nil {
continue // keep trying
}
for _, device := range devices {
// check if this is our emulator by matching the AVD name
if device.Platform() == "android" && device.DeviceType() == "emulator" {
// device.ID() now returns the AVD name for emulators
if device.ID() == avdName || matchesAVDName(avdName, device.Name()) {
// found our emulator, check if it's fully booted
// need to get the transport ID for the boot check
if androidDev, ok := device.(*AndroidDevice); ok {
transportID := androidDev.transportID
if transportID == "" {
transportID = androidDev.id
}
bootComplete, _ := d.checkBootComplete(transportID)
if bootComplete {
return androidDev.transportID, nil
}
}
}
}
}
}
}
}
// Boot launches an offline Android emulator and waits for it to be ready
func (d *AndroidDevice) Boot() error {
if d.state != "offline" {
return fmt.Errorf("emulator is already running")
}
utils.Verbose("Starting Android emulator: %s", d.id)
// create context with timeout for the boot wait process
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
// launch emulator in background without context (so it persists after function returns)
cmd := exec.Command(getEmulatorPath(), "-netdelay", "none", "-netspeed", "full", "-avd", d.id, "-qt-hide-window")
err := cmd.Start()
if err != nil {
return fmt.Errorf("failed to start emulator: %w", err)
}
// monitor context cancellation to clean up the process only on timeout
go func() {
<-ctx.Done()
if cmd.Process != nil && ctx.Err() == context.DeadlineExceeded {
utils.Verbose("Boot timeout exceeded, killing emulator process")
_ = cmd.Process.Kill()
}
}()
utils.Verbose("Waiting for emulator to boot...")
// wait for emulator to boot and get its actual device ID
deviceID, err := d.waitForEmulatorBootComplete(ctx, d.id)
if err != nil {
// if boot failed, kill the emulator process
if cmd.Process != nil {
_ = cmd.Process.Kill()
}
return err
}
utils.Verbose("Emulator booted successfully with transport ID: %s", deviceID)
// update our transport ID to the actual emulator-XXXX ID
// the device ID (d.id) is already set to the AVD name and should not change
d.transportID = deviceID
d.state = "online"
return nil
}
// checkBootComplete checks if an emulator has finished booting
func (d *AndroidDevice) checkBootComplete(deviceID string) (bool, error) {
cmd := exec.Command(getAdbPath(), "-s", deviceID, "shell", "getprop", "sys.boot_completed")
output, err := cmd.CombinedOutput()
if err != nil {
return false, err
}
return strings.TrimSpace(string(output)) == "1", nil
}
func (d *AndroidDevice) PressButton(key string) error {
keyMap := map[string]string{
"HOME": "KEYCODE_HOME",
"BACK": "KEYCODE_BACK",
"VOLUME_UP": "KEYCODE_VOLUME_UP",
"VOLUME_DOWN": "KEYCODE_VOLUME_DOWN",
"ENTER": "KEYCODE_ENTER",
"DPAD_CENTER": "KEYCODE_DPAD_CENTER",
"DPAD_UP": "KEYCODE_DPAD_UP",
"DPAD_DOWN": "KEYCODE_DPAD_DOWN",
"DPAD_LEFT": "KEYCODE_DPAD_LEFT",
"DPAD_RIGHT": "KEYCODE_DPAD_RIGHT",
"BACKSPACE": "KEYCODE_DEL",
"APP_SWITCH": "KEYCODE_APP_SWITCH",
"POWER": "KEYCODE_POWER",
}
keycode, exists := keyMap[key]
if !exists {
return fmt.Errorf("AndroidDevice: unsupported button key: %s", key)
}
output, err := d.runAdbCommand("shell", "input", "keyevent", keycode)
if err != nil {
return fmt.Errorf("AndroidDevice: failed to press %s button: %v\nOutput: %s", key, err, string(output))
}
return nil
}
// isDeviceKitInstalled checks if DeviceKit is installed on the device
func (d *AndroidDevice) isDeviceKitInstalled() bool {
appPath, err := d.GetAppPath("com.mobilenext.devicekit")
return err == nil && appPath != ""
}
// isAscii checks if text contains only ASCII characters
func isAscii(text string) bool {
for _, char := range text {
if char > 127 {
return false
}
}
return true
}
// escapeShellText escapes shell special characters
func escapeShellText(text string) string {
// escape all shell special characters that could be used for injection
specialChars := `\'"`+ "`" + `
|&;()<>{}[]$*? `
result := ""
for _, char := range text {
if strings.ContainsRune(specialChars, char) {
result += "\\"
}
result += string(char)
}
return result
}
func (d *AndroidDevice) SendKeys(text string) error {
if text == "" {
// bailing early, so we don't run adb shell with empty string.
// this happens when you prompt with a simple "submit".
return nil
}
switch text {
case "\b":
return d.PressButton("BACKSPACE")
case "\n":
return d.PressButton("ENTER")
}
if isAscii(text) {
// adb shell input only supports ascii characters. and
// some of the keys have to be escaped.
escapedText := escapeShellText(text)
_, err := d.runAdbCommand("shell", "input", "text", escapedText)
return err
}
// try sending over clipboard if DeviceKit is installed
if d.isDeviceKitInstalled() {
// ensure clipboard is always cleared, even on failure
defer func() {
_, _ = d.runAdbCommand("shell", "am", "broadcast", "-a", "devicekit.clipboard.clear", "-n", "com.mobilenext.devicekit/.ClipboardBroadcastReceiver")
}()
// encode text as base64
base64Text := base64.StdEncoding.EncodeToString([]byte(text))
// send clipboard over and immediately paste it
_, err := d.runAdbCommand("shell", "am", "broadcast", "-a", "devicekit.clipboard.set", "-e", "encoding", "base64", "-e", "text", base64Text, "-n", "com.mobilenext.devicekit/.ClipboardBroadcastReceiver")
if err != nil {
return fmt.Errorf("failed to set clipboard: %w", err)
}
_, err = d.runAdbCommand("shell", "input", "keyevent", "KEYCODE_PASTE")
if err != nil {
return fmt.Errorf("failed to paste: %w", err)
}
return nil
}
return fmt.Errorf("non-ASCII text is not supported on Android, please install mobilenext devicekit, see https://github.com/mobile-next/devicekit-android")
}
func (d *AndroidDevice) OpenURL(url string) error {
output, err := d.runAdbCommand("shell", "am", "start", "-a", "android.intent.action.VIEW", "-d", url)
if err != nil {
return fmt.Errorf("failed to open URL %s: %v\nOutput: %s", url, err, string(output))
}
return nil
}
func (d *AndroidDevice) ListApps() ([]InstalledAppInfo, error) {
output, err := d.runAdbCommand("shell", "cmd", "package", "query-activities", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER")
if err != nil {
return nil, fmt.Errorf("failed to query launcher activities: %v", err)
}
lines := strings.Split(string(output), "\n")
var packageNames []string
seen := make(map[string]bool)
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "packageName=") {
packageName := strings.TrimPrefix(line, "packageName=")
if !seen[packageName] {
seen[packageName] = true
packageNames = append(packageNames, packageName)
}
}
}
var apps []InstalledAppInfo
for _, packageName := range packageNames {
apps = append(apps, InstalledAppInfo{
PackageName: packageName,
})
}
return apps, nil
}
func (d *AndroidDevice) getForegroundPackageName() (string, error) {
output, err := d.runAdbCommand("shell", "dumpsys", "window", "displays")
if err != nil {
return "", fmt.Errorf("failed to get window displays: %w", err)
}
// parse package name from mCurrentFocus line
// format: mCurrentFocus=Window{...u0 com.package.name/...}
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if strings.Contains(line, "mCurrentFocus") {
parts := strings.Fields(line)
if len(parts) >= 3 {
focusPart := parts[2]
// extract package name (before the '/')
if idx := strings.Index(focusPart, "/"); idx != -1 {
return focusPart[:idx], nil
}
}
break
}
}
return "", fmt.Errorf("could not determine foreground app")
}
func (d *AndroidDevice) getAppVersion(packageName string) (string, error) {
output, err := d.runAdbCommand("shell", "dumpsys", "package", packageName)
if err != nil {
return "", fmt.Errorf("failed to get package info: %w", err)
}
// parse version name
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if strings.Contains(line, "versionName=") {
parts := strings.Split(line, "versionName=")
if len(parts) >= 2 {
return strings.TrimSpace(parts[1]), nil
}
break
}
}
return "", nil
}
func (d *AndroidDevice) GetForegroundApp() (*ForegroundAppInfo, error) {
packageName, err := d.getForegroundPackageName()
if err != nil {
return nil, err
}
version, err := d.getAppVersion(packageName)
if err != nil {
return nil, err
}
return &ForegroundAppInfo{
PackageName: packageName,
AppName: packageName,
Version: version,
}, nil
}
func (d *AndroidDevice) Info() (*FullDeviceInfo, error) {
// run adb shell wm size
output, err := d.runAdbCommand("shell", "wm", "size")
if err != nil {
return nil, fmt.Errorf("failed to get screen size: %v", err)
}
// split result by space, and then take 2nd argument split by "x"
screenSize := strings.Split(string(output), " ")
pair := strings.Trim(screenSize[len(screenSize)-1], "\r\n")
parts := strings.SplitN(pair, "x", 2)
widthInt, err := strconv.Atoi(parts[0])
if err != nil {
return nil, fmt.Errorf("failed to get screen size: %v", err)
}
heightInt, err := strconv.Atoi(parts[1])
if err != nil {
return nil, fmt.Errorf("failed to get screen size: %v", err)
}
return &FullDeviceInfo{
DeviceInfo: DeviceInfo{
ID: d.ID(),
Name: d.Name(),
Platform: d.Platform(),
Type: d.DeviceType(),
Version: d.Version(),
State: d.State(),
Model: d.model,
},
ScreenSize: &ScreenSize{
Width: widthInt,
Height: heightInt,
Scale: 1,
},
}, nil
}
func (d *AndroidDevice) GetAppPath(packageName string) (string, error) {
output, err := d.runAdbCommand("shell", "pm", "path", packageName)
if err != nil {
// best effort (pm path will return error code 1)
return "", nil
}
// remove the "package:" prefix
appPath := strings.TrimPrefix(string(output), "package:")
// trim all whitespace including \r\n (CRLF on Windows)
appPath = strings.TrimSpace(appPath)
return appPath, nil
}
func (d *AndroidDevice) StartScreenCapture(config ScreenCaptureConfig) error {
if config.Format != "mjpeg" && config.Format != "avc" {
return fmt.Errorf("unsupported format: %s, only 'mjpeg' and 'avc' are supported", config.Format)
}
if config.OnProgress != nil {
config.OnProgress("Installing Agent")
}
utils.Verbose("Ensuring DeviceKit is installed...")
err := d.EnsureDeviceKitInstalled()
if err != nil {
return fmt.Errorf("failed to ensure DeviceKit is installed: %v", err)
}
appPath, err := d.GetAppPath("com.mobilenext.devicekit")
if err != nil {
return fmt.Errorf("failed to get app path: %v", err)
}
var serverClass string
if config.Format == "mjpeg" {
serverClass = "com.mobilenext.devicekit.MjpegServer"
} else {
serverClass = "com.mobilenext.devicekit.AvcServer"
}
if config.OnProgress != nil {
config.OnProgress("Starting Agent")
}
utils.Verbose("Starting %s with app path: %s", serverClass, appPath)
cmdArgs := append([]string{"-s", d.getAdbIdentifier()}, "exec-out", fmt.Sprintf("CLASSPATH=%s", appPath), "app_process", "/system/bin", serverClass, "--quality", fmt.Sprintf("%d", config.Quality), "--scale", fmt.Sprintf("%.2f", config.Scale), "--fps", fmt.Sprintf("%d", config.FPS))
utils.Verbose("Running command: %s %s", getAdbPath(), strings.Join(cmdArgs, " "))
cmd := exec.Command(getAdbPath(), cmdArgs...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("failed to create stdout pipe: %v", err)
}
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start %s: %v", serverClass, err)
}
// Read bytes from the command output and send to callback
buffer := make([]byte, 65536)
for {
n, err := stdout.Read(buffer)
if err != nil {
break
}
if n > 0 {
// Send bytes to callback, break if it returns false
if !config.OnData(buffer[:n]) {
break
}
}
}
_ = cmd.Process.Kill()
return nil
}
// ScreenRecord records the device screen to a local MP4 file using adb screenrecord.
// blocks until Ctrl+C is pressed, stopChan is closed, or the time limit is reached.
// when stopChan is nil, behavior is unchanged (CLI usage).
func (d *AndroidDevice) ScreenRecord(localOutput string, timeLimit int, stopChan <-chan struct{}) error {
if stopChan == nil {
stopChan = make(chan struct{})
}
remotePath := fmt.Sprintf("/sdcard/mobilecli-rec-%d.mp4", time.Now().UnixNano())
args := []string{"-s", d.getAdbIdentifier(), "shell", "screenrecord"}
if timeLimit > 0 {
args = append(args, "--time-limit", fmt.Sprintf("%d", timeLimit))
}
args = append(args, remotePath)
utils.Verbose("Running: %s %s", getAdbPath(), strings.Join(args, " "))
cmd := exec.Command(getAdbPath(), args...)
// handle Ctrl+C: adb child gets SIGINT from process group automatically,
// which causes screenrecord to finalize the MP4 and exit.
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
if err := cmd.Start(); err != nil {
signal.Stop(sigChan)
return fmt.Errorf("failed to start screenrecord: %w", err)
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
case <-sigChan:
// send SIGINT to child explicitly so it finalizes the MP4
if cmd.Process != nil {
_ = cmd.Process.Signal(syscall.SIGINT)
}
<-done
case <-stopChan: