-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathandroid.ts
More file actions
363 lines (303 loc) · 10.5 KB
/
android.ts
File metadata and controls
363 lines (303 loc) · 10.5 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
import path from "path";
import { execFileSync } from "child_process";
import * as xml from "fast-xml-parser";
import { ActionableError, Button, InstalledApp, Robot, ScreenElement, ScreenElementRect, ScreenSize, SwipeDirection, Orientation } from "./robot";
export interface AndroidDevice {
deviceId: string;
deviceType: "tv" | "mobile";
}
interface UiAutomatorXmlNode {
node: UiAutomatorXmlNode[];
class?: string;
text?: string;
bounds?: string;
hint?: string;
focused?: string;
clickable?: string;
focusable?: string;
enabled?: string;
selected?: string;
package?: string;
"content-desc"?: string;
"resource-id"?: string;
}
interface UiAutomatorXml {
hierarchy: {
node: UiAutomatorXmlNode;
};
}
const getAdbPath = (): string => {
let executable = "adb";
if (process.env.ANDROID_HOME) {
executable = path.join(process.env.ANDROID_HOME, "platform-tools", "adb");
}
return executable;
};
const BUTTON_MAP: Record<Button, string> = {
"BACK": "KEYCODE_BACK",
"HOME": "KEYCODE_HOME",
"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",
};
const TIMEOUT = 30000;
const MAX_BUFFER_SIZE = 1024 * 1024 * 4;
type AndroidDeviceType = "tv" | "mobile";
export class AndroidRobot implements Robot {
public constructor(private deviceId: string) {
}
public adb(...args: string[]): Buffer {
return execFileSync(getAdbPath(), ["-s", this.deviceId, ...args], {
maxBuffer: MAX_BUFFER_SIZE,
timeout: TIMEOUT,
});
}
public getSystemFeatures(): string[] {
return this.adb("shell", "pm", "list", "features")
.toString()
.split("\n")
.map(line => line.trim())
.filter(line => line.startsWith("feature:"))
.map(line => line.substring("feature:".length));
}
public async getScreenSize(): Promise<ScreenSize> {
const screenSize = this.adb("shell", "wm", "size")
.toString()
.split(" ")
.pop();
if (!screenSize) {
throw new Error("Failed to get screen size");
}
const scale = 1;
const [width, height] = screenSize.split("x").map(Number);
return { width, height, scale };
}
public async listApps(): Promise<InstalledApp[]> {
return this.adb("shell", "cmd", "package", "query-activities", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER")
.toString()
.split("\n")
.map(line => line.trim())
.filter(line => line.startsWith("packageName="))
.map(line => line.substring("packageName=".length))
.filter((value, index, self) => self.indexOf(value) === index)
.map(packageName => ({
packageName,
appName: packageName,
}));
}
public async launchApp(packageName: string): Promise<void> {
this.adb("shell", "monkey", "-p", packageName, "-c", "android.intent.category.LAUNCHER", "1");
}
public async listRunningProcesses(): Promise<string[]> {
return this.adb("shell", "ps", "-e")
.toString()
.split("\n")
.map(line => line.trim())
.filter(line => line.startsWith("u")) // non-system processes
.map(line => line.split(/\s+/)[8]); // get process name
}
public async swipe(direction: SwipeDirection): Promise<void> {
const screenSize = await this.getScreenSize();
const centerX = screenSize.width >> 1;
let x0: number, y0: number, x1: number, y1: number;
switch (direction) {
case "up":
x0 = x1 = centerX;
y0 = Math.floor(screenSize.height * 0.80);
y1 = Math.floor(screenSize.height * 0.20);
break;
case "down":
x0 = x1 = centerX;
y0 = Math.floor(screenSize.height * 0.20);
y1 = Math.floor(screenSize.height * 0.80);
break;
case "left":
x0 = Math.floor(screenSize.width * 0.80);
x1 = Math.floor(screenSize.width * 0.20);
y0 = y1 = Math.floor(screenSize.height * 0.50);
break;
case "right":
x0 = Math.floor(screenSize.width * 0.20);
x1 = Math.floor(screenSize.width * 0.80);
y0 = y1 = Math.floor(screenSize.height * 0.50);
break;
default:
throw new ActionableError(`Swipe direction "${direction}" is not supported`);
}
this.adb("shell", "input", "swipe", `${x0}`, `${y0}`, `${x1}`, `${y1}`, "1000");
}
public async swipeFromCoordinate(x: number, y: number, direction: SwipeDirection, distance?: number): Promise<void> {
const screenSize = await this.getScreenSize();
let x0: number, y0: number, x1: number, y1: number;
// Use provided distance or default to 30% of screen dimension
const defaultDistanceY = Math.floor(screenSize.height * 0.3);
const defaultDistanceX = Math.floor(screenSize.width * 0.3);
const swipeDistanceY = distance || defaultDistanceY;
const swipeDistanceX = distance || defaultDistanceX;
switch (direction) {
case "up":
x0 = x1 = x;
y0 = y;
y1 = Math.max(0, y - swipeDistanceY);
break;
case "down":
x0 = x1 = x;
y0 = y;
y1 = Math.min(screenSize.height, y + swipeDistanceY);
break;
case "left":
x0 = x;
x1 = Math.max(0, x - swipeDistanceX);
y0 = y1 = y;
break;
case "right":
x0 = x;
x1 = Math.min(screenSize.width, x + swipeDistanceX);
y0 = y1 = y;
break;
default:
throw new ActionableError(`Swipe direction "${direction}" is not supported`);
}
this.adb("shell", "input", "swipe", `${x0}`, `${y0}`, `${x1}`, `${y1}`, "1000");
}
public async getScreenshot(): Promise<Buffer> {
return this.adb("exec-out", "screencap", "-p");
}
private collectElements(node: UiAutomatorXmlNode): ScreenElement[] {
const elements: Array<ScreenElement> = [];
if (node.node) {
if (Array.isArray(node.node)) {
for (const childNode of node.node) {
elements.push(...this.collectElements(childNode));
}
} else {
elements.push(...this.collectElements(node.node));
}
}
// Include elements with text/labels OR clickable/focusable elements (like icons, buttons)
const hasTextOrLabel = node.text || node["content-desc"] || node.hint || node["resource-id"];
const isInteractive = node.clickable === "true" || node.focusable === "true" ||
(node.class && (node.class.includes("Button") || node.class.includes("ImageView") ||
node.class.includes("ImageButton") || node.class.includes("View")));
if (hasTextOrLabel || isInteractive) {
const element: ScreenElement = {
type: node.class || "element",
text: node.text,
label: node["resource-id"] || node["content-desc"] || node.hint || "",
rect: this.getScreenElementRect(node),
};
if (node.focused === "true") {
// only provide it if it's true, otherwise don't confuse llm
element.focused = true;
}
const resourceId = node["resource-id"];
if (resourceId !== null && resourceId !== "") {
element.identifier = resourceId;
}
if (element.rect.width > 0 && element.rect.height > 0) {
elements.push(element);
}
}
return elements;
}
public async getElementsOnScreen(): Promise<ScreenElement[]> {
const parsedXml = await this.getUiAutomatorXml();
const hierarchy = parsedXml.hierarchy;
const elements = this.collectElements(hierarchy.node);
return elements;
}
public async terminateApp(packageName: string): Promise<void> {
this.adb("shell", "am", "force-stop", packageName);
}
public async openUrl(url: string): Promise<void> {
this.adb("shell", "am", "start", "-a", "android.intent.action.VIEW", "-d", url);
}
public async sendKeys(text: string): Promise<void> {
// adb shell requires some escaping
const _text = text.replace(/ /g, "\\ ");
this.adb("shell", "input", "text", _text);
}
public async pressButton(button: Button) {
if (!BUTTON_MAP[button]) {
throw new ActionableError(`Button "${button}" is not supported`);
}
this.adb("shell", "input", "keyevent", BUTTON_MAP[button]);
}
public async tap(x: number, y: number): Promise<void> {
this.adb("shell", "input", "tap", `${x}`, `${y}`);
}
public async setOrientation(orientation: Orientation): Promise<void> {
const orientationValue = orientation === "portrait" ? 0 : 1;
// disable auto-rotation prior to setting the orientation
this.adb("shell", "settings", "put", "system", "accelerometer_rotation", "0");
this.adb("shell", "content", "insert", "--uri", "content://settings/system", "--bind", "name:s:user_rotation", "--bind", `value:i:${orientationValue}`);
}
public async getOrientation(): Promise<Orientation> {
const rotation = this.adb("shell", "settings", "get", "system", "user_rotation").toString().trim();
return rotation === "0" ? "portrait" : "landscape";
}
private async getUiAutomatorDump(): Promise<string> {
for (let tries = 0; tries < 10; tries++) {
const dump = this.adb("exec-out", "uiautomator", "dump", "/dev/tty").toString();
// note: we're not catching other errors here. maybe we should check for <?xml
if (dump.includes("null root node returned by UiTestAutomationBridge")) {
// uncomment for debugging
// const screenshot = await this.getScreenshot();
// console.error("Failed to get UIAutomator XML. Here's a screenshot: " + screenshot.toString("base64"));
continue;
}
return dump.substring(dump.indexOf("<?xml"));
}
throw new ActionableError("Failed to get UIAutomator XML");
}
private async getUiAutomatorXml(): Promise<UiAutomatorXml> {
const dump = await this.getUiAutomatorDump();
const parser = new xml.XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "",
});
return parser.parse(dump) as UiAutomatorXml;
}
private getScreenElementRect(node: UiAutomatorXmlNode): ScreenElementRect {
const bounds = String(node.bounds);
const [, left, top, right, bottom] = bounds.match(/^\[(\d+),(\d+)\]\[(\d+),(\d+)\]$/)?.map(Number) || [];
return {
x: left,
y: top,
width: right - left,
height: bottom - top,
};
}
}
export class AndroidDeviceManager {
private getDeviceType(name: string): AndroidDeviceType {
const device = new AndroidRobot(name);
const features = device.getSystemFeatures();
if (features.includes("android.software.leanback") || features.includes("android.hardware.type.television")) {
return "tv";
}
return "mobile";
}
public getConnectedDevices(): AndroidDevice[] {
try {
const names = execFileSync(getAdbPath(), ["devices"])
.toString()
.split("\n")
.filter(line => !line.startsWith("List of devices attached"))
.filter(line => line.trim() !== "")
.map(line => line.split("\t")[0]);
return names.map(name => ({
deviceId: name,
deviceType: this.getDeviceType(name),
}));
} catch (error) {
console.error("Could not execute adb command, maybe ANDROID_HOME is not set?");
return [];
}
}
}