microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.17.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/android/adb.ts

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