microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.11.2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/extension/android/adb.ts

214lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as Q from "q";
5
6import { ChildProcess, ISpawnResult } from "../../common/node/childProcess";
7import { CommandExecutor } from "../../common/commandExecutor";
8import * as path from "path";
9import * as fs from "fs";
10import { ILogger } from "../log/LogHelper";
11import * as os from "os";
12import * as nls from "vscode-nls";
13const localize = nls.loadMessageBundle();
14
15// See android versions usage at: http://developer.android.com/about/dashboards/index.html
16export enum AndroidAPILevel {
17 Marshmallow = 23,
18 LOLLIPOP_MR1 = 22,
19 LOLLIPOP = 21, /* Supports adb reverse */
20 KITKAT = 19,
21 JELLY_BEAN_MR2 = 18,
22 JELLY_BEAN_MR1 = 17,
23 JELLY_BEAN = 16,
24 ICE_CREAM_SANDWICH_MR1 = 15,
25 GINGERBREAD_MR1 = 10,
26}
27
28enum KeyEvents {
29 KEYCODE_BACK = 4,
30 KEYCODE_DPAD_UP = 19,
31 KEYCODE_DPAD_DOWN = 20,
32 KEYCODE_DPAD_CENTER = 23,
33 KEYCODE_MENU = 82,
34}
35
36export enum DeviceType {
37 AndroidSdkEmulator, // These seem to have emulator-<port> ids
38 Other,
39}
40
41export interface IDevice {
42 id: string;
43 isOnline: boolean;
44 type: DeviceType;
45}
46
47const AndroidSDKEmulatorPattern = /^emulator-\d{1,5}$/;
48
49export class AdbHelper {
50 private childProcess: ChildProcess = new ChildProcess();
51 private commandExecutor: CommandExecutor = new CommandExecutor();
52 private adbExecutable: string = "";
53 private launchActivity: string;
54
55 constructor(projectRoot: string, logger?: ILogger, launchActivity: string = "MainActivity") {
56
57 // Trying to read sdk location from local.properties file and if we succueded then
58 // we would run adb from inside it, otherwise we would rely to PATH
59 const sdkLocation = this.getSdkLocationFromLocalPropertiesFile(projectRoot, logger);
60 this.adbExecutable = sdkLocation ? `${path.join(sdkLocation, "platform-tools", "adb")}` : "adb";
61 this.launchActivity = launchActivity;
62 }
63
64 /**
65 * Gets the list of Android connected devices and emulators.
66 */
67 public getConnectedDevices(): Q.Promise<IDevice[]> {
68 return this.childProcess.execToString(`${this.adbExecutable} devices`)
69 .then(output => {
70 return this.parseConnectedDevices(output);
71 });
72 }
73
74 public setLaunchActivity(launchActivity: string): void {
75 this.launchActivity = launchActivity;
76 }
77
78 /**
79 * Broadcasts an intent to reload the application in debug mode.
80 */
81 public switchDebugMode(projectRoot: string, packageName: string, enable: boolean, debugTarget?: string): Q.Promise<void> {
82 let enableDebugCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am broadcast -a "${packageName}.RELOAD_APP_ACTION" --ez jsproxy ${enable}`;
83 return new CommandExecutor(projectRoot).execute(enableDebugCommand)
84 .then(() => { // We should stop and start application again after RELOAD_APP_ACTION, otherwise app going to hangs up
85 let deferred = Q.defer();
86 setTimeout(() => {
87 this.stopApp(projectRoot, packageName, debugTarget)
88 .then(() => {
89 return deferred.resolve({});
90 });
91 }, 200); // We need a little delay after broadcast command
92
93 return deferred.promise;
94 })
95 .then(() => {
96 return this.launchApp(projectRoot, packageName, debugTarget);
97 });
98 }
99
100 /**
101 * Sends an intent which launches the main activity of the application.
102 */
103 public launchApp(projectRoot: string, packageName: string, debugTarget?: string): Q.Promise<void> {
104 let launchAppCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am start -n ${packageName}/.${this.launchActivity}`;
105 return new CommandExecutor(projectRoot).execute(launchAppCommand);
106 }
107
108 public stopApp(projectRoot: string, packageName: string, debugTarget?: string): Q.Promise<void> {
109 let stopAppCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am force-stop ${packageName}`;
110 return new CommandExecutor(projectRoot).execute(stopAppCommand);
111 }
112
113 public apiVersion(deviceId: string): Q.Promise<AndroidAPILevel> {
114 return this.executeQuery(deviceId, "shell getprop ro.build.version.sdk").then(output =>
115 parseInt(output, 10));
116 }
117
118 public reverseAdb(deviceId: string, packagerPort: number): Q.Promise<void> {
119 return this.execute(deviceId, `reverse tcp:${packagerPort} tcp:${packagerPort}`);
120 }
121
122 public showDevMenu(deviceId?: string): Q.Promise<void> {
123 let command = `${this.adbExecutable} ${deviceId ? "-s " + deviceId : ""} shell input keyevent ${KeyEvents.KEYCODE_MENU}`;
124 return this.commandExecutor.execute(command);
125 }
126
127 public reloadApp(deviceId?: string): Q.Promise<void> {
128 let command = `${this.adbExecutable} ${deviceId ? "-s " + deviceId : ""} shell input text "RR"`;
129 return this.commandExecutor.execute(command);
130 }
131
132 public getOnlineDevices(): Q.Promise<IDevice[]> {
133 return this.getConnectedDevices().then(devices => {
134 return devices.filter(device =>
135 device.isOnline);
136 });
137 }
138
139 public startLogCat(adbParameters: string[]): ISpawnResult {
140 return new ChildProcess().spawn(`${this.adbExecutable}`, adbParameters);
141 }
142
143 public parseSdkLocation(fileContent: string, logger?: ILogger) {
144 const matches = fileContent.match(/^sdk\.dir=(.+)$/m);
145 if (!matches || !matches[1]) {
146 if (logger) {
147 logger.info(localize("NoSdkDirFoundInLocalPropertiesFile", "No sdk.dir value found in local.properties file. Using Android SDK location from PATH."));
148 }
149 return null;
150 }
151
152 let sdkLocation = matches[1].trim();
153 if (os.platform() === "win32") {
154 // For Windows we need to unescape files separators and drive letter separators
155 sdkLocation = sdkLocation.replace(/\\\\/g, "\\").replace("\\:", ":");
156 }
157 if (logger) {
158 logger.info(localize("UsindAndroidSDKLocationDefinedInLocalPropertiesFile", "Using Android SDK location defined in android/local.properties file: {0}.", sdkLocation));
159 }
160
161 return sdkLocation;
162 }
163
164 private parseConnectedDevices(input: string): IDevice[] {
165 let result: IDevice[] = [];
166 let regex = new RegExp("^(\\S+)\\t(\\S+)$", "mg");
167 let match = regex.exec(input);
168 while (match != null) {
169 result.push({ id: match[1], isOnline: match[2] === "device", type: this.extractDeviceType(match[1]) });
170 match = regex.exec(input);
171 }
172 return result;
173 }
174
175 private extractDeviceType(id: string): DeviceType {
176 return id.match(AndroidSDKEmulatorPattern)
177 ? DeviceType.AndroidSdkEmulator
178 : DeviceType.Other;
179 }
180
181 private executeQuery(deviceId: string, command: string): Q.Promise<string> {
182 return this.childProcess.execToString(this.generateCommandForDevice(deviceId, command));
183 }
184
185 private execute(deviceId: string, command: string): Q.Promise<void> {
186 return this.commandExecutor.execute(this.generateCommandForDevice(deviceId, command));
187 }
188
189 private generateCommandForDevice(deviceId: string, adbCommand: string): string {
190 return `${this.adbExecutable} -s "${deviceId}" ${adbCommand}`;
191 }
192
193 private getSdkLocationFromLocalPropertiesFile(projectRoot: string, logger?: ILogger): string | null {
194 const localPropertiesFilePath = path.join(projectRoot, "android", "local.properties");
195 if (!fs.existsSync(localPropertiesFilePath)) {
196 if (logger) {
197 logger.info(localize("LocalPropertiesFileDoesNotExist", "local.properties file doesn't exist. Using Android SDK location from PATH."));
198 }
199 return null;
200 }
201
202 let fileContent: string;
203 try {
204 fileContent = fs.readFileSync(localPropertiesFilePath).toString();
205 } catch (e) {
206 if (logger) {
207 logger.error(localize("CouldNotReadFrom", "Couldn't read from {0}.", localPropertiesFilePath), e, e.stack);
208 logger.info(localize("UsingAndroidSDKLocationFromPATH", "Using Android SDK location from PATH."));
209 }
210 return null;
211 }
212 return this.parseSdkLocation(fileContent, logger);
213 }
214}
215