microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
ff70c05a6c821e99785e3f91dca1daf27094e4fd

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/android/adb.ts

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