microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.11.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/android/adb.ts

214lines · modeblame

52f3873ddigeff10 years ago1// 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
db6fd42aRuslan Bikkinin7 years ago6import { 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";
8b383051Ruslan Bikkinin7 years ago11import * as os from "os";
d7d405aeYuri Skorokhodov7 years ago12import * as nls from "vscode-nls";
13const localize = nls.loadMessageBundle();
52f3873ddigeff10 years ago14
ce7fd946digeff10 years ago15// See android versions usage at: http://developer.android.com/about/dashboards/index.html
52f3873ddigeff10 years ago16export enum AndroidAPILevel {
ce7fd946digeff10 years ago17Marshmallow = 23,
52f3873ddigeff10 years ago18LOLLIPOP_MR1 = 22,
19LOLLIPOP = 21, /* Supports adb reverse */
20KITKAT = 19,
21JELLY_BEAN_MR2 = 18,
22JELLY_BEAN_MR1 = 17,
23JELLY_BEAN = 16,
24ICE_CREAM_SANDWICH_MR1 = 15,
25GINGERBREAD_MR1 = 10,
26}
27
7daed3fcArtem Egorov8 years ago28enum KeyEvents {
29KEYCODE_BACK = 4,
30KEYCODE_DPAD_UP = 19,
31KEYCODE_DPAD_DOWN = 20,
32KEYCODE_DPAD_CENTER = 23,
33KEYCODE_MENU = 82,
34}
35
52f3873ddigeff10 years ago36export enum DeviceType {
37AndroidSdkEmulator, // These seem to have emulator-<port> ids
27710197Vladimir Kotikov8 years ago38Other,
52f3873ddigeff10 years ago39}
40
41export interface IDevice {
42id: string;
43isOnline: boolean;
44type: DeviceType;
45}
46
7daed3fcArtem Egorov8 years ago47const AndroidSDKEmulatorPattern = /^emulator-\d{1,5}$/;
52f3873ddigeff10 years ago48
7daed3fcArtem Egorov8 years ago49export class AdbHelper {
db6fd42aRuslan Bikkinin7 years ago50private childProcess: ChildProcess = new ChildProcess();
51private commandExecutor: CommandExecutor = new CommandExecutor();
52private adbExecutable: string = "";
78c2b4deRedMickey6 years ago53private launchActivity: string;
db6fd42aRuslan Bikkinin7 years ago54
78c2b4deRedMickey6 years ago55constructor(projectRoot: string, logger?: ILogger, launchActivity: string = "MainActivity") {
db6fd42aRuslan Bikkinin7 years ago56
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
59const sdkLocation = this.getSdkLocationFromLocalPropertiesFile(projectRoot, logger);
60this.adbExecutable = sdkLocation ? `${path.join(sdkLocation, "platform-tools", "adb")}` : "adb";
78c2b4deRedMickey6 years ago61this.launchActivity = launchActivity;
db6fd42aRuslan Bikkinin7 years ago62}
52f3873ddigeff10 years ago63
64/**
65* Gets the list of Android connected devices and emulators.
66*/
db6fd42aRuslan Bikkinin7 years ago67public getConnectedDevices(): Q.Promise<IDevice[]> {
68return this.childProcess.execToString(`${this.adbExecutable} devices`)
52f3873ddigeff10 years ago69.then(output => {
70return this.parseConnectedDevices(output);
71});
72}
73
78c2b4deRedMickey6 years ago74public setLaunchActivity(launchActivity: string): void {
75this.launchActivity = launchActivity;
76}
77
52f3873ddigeff10 years ago78/**
79* Broadcasts an intent to reload the application in debug mode.
80*/
db6fd42aRuslan Bikkinin7 years ago81public switchDebugMode(projectRoot: string, packageName: string, enable: boolean, debugTarget?: string): Q.Promise<void> {
82let enableDebugCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am broadcast -a "${packageName}.RELOAD_APP_ACTION" --ez jsproxy ${enable}`;
b57ea017Artem Egorov8 years ago83return new CommandExecutor(projectRoot).execute(enableDebugCommand)
84.then(() => { // We should stop and start application again after RELOAD_APP_ACTION, otherwise app going to hangs up
85let deferred = Q.defer();
86setTimeout(() => {
87this.stopApp(projectRoot, packageName, debugTarget)
88.then(() => {
89return deferred.resolve({});
90});
91}, 200); // We need a little delay after broadcast command
92
93return deferred.promise;
94})
95.then(() => {
96return this.launchApp(projectRoot, packageName, debugTarget);
97});
52f3873ddigeff10 years ago98}
99
100/**
101* Sends an intent which launches the main activity of the application.
102*/
db6fd42aRuslan Bikkinin7 years ago103public launchApp(projectRoot: string, packageName: string, debugTarget?: string): Q.Promise<void> {
78c2b4deRedMickey6 years ago104let launchAppCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am start -n ${packageName}/.${this.launchActivity}`;
52f3873ddigeff10 years ago105return new CommandExecutor(projectRoot).execute(launchAppCommand);
106}
107
db6fd42aRuslan Bikkinin7 years ago108public stopApp(projectRoot: string, packageName: string, debugTarget?: string): Q.Promise<void> {
109let stopAppCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am force-stop ${packageName}`;
b57ea017Artem Egorov8 years ago110return new CommandExecutor(projectRoot).execute(stopAppCommand);
111}
112
db6fd42aRuslan Bikkinin7 years ago113public apiVersion(deviceId: string): Q.Promise<AndroidAPILevel> {
52f3873ddigeff10 years ago114return this.executeQuery(deviceId, "shell getprop ro.build.version.sdk").then(output =>
115parseInt(output, 10));
116}
117
db6fd42aRuslan Bikkinin7 years ago118public reverseAdb(deviceId: string, packagerPort: number): Q.Promise<void> {
b57ea017Artem Egorov8 years ago119return this.execute(deviceId, `reverse tcp:${packagerPort} tcp:${packagerPort}`);
52f3873ddigeff10 years ago120}
121
db6fd42aRuslan Bikkinin7 years ago122public showDevMenu(deviceId?: string): Q.Promise<void> {
123let command = `${this.adbExecutable} ${deviceId ? "-s " + deviceId : ""} shell input keyevent ${KeyEvents.KEYCODE_MENU}`;
7daed3fcArtem Egorov8 years ago124return this.commandExecutor.execute(command);
125}
126
db6fd42aRuslan Bikkinin7 years ago127public reloadApp(deviceId?: string): Q.Promise<void> {
e23ea82cAlter Code7 years ago128let command = `${this.adbExecutable} ${deviceId ? "-s " + deviceId : ""} shell input text "RR"`;
129return this.commandExecutor.execute(command);
7daed3fcArtem Egorov8 years ago130}
131
db6fd42aRuslan Bikkinin7 years ago132public getOnlineDevices(): Q.Promise<IDevice[]> {
7daed3fcArtem Egorov8 years ago133return this.getConnectedDevices().then(devices => {
134return devices.filter(device =>
135device.isOnline);
136});
137}
138
db6fd42aRuslan Bikkinin7 years ago139public startLogCat(adbParameters: string[]): ISpawnResult {
140return new ChildProcess().spawn(`${this.adbExecutable}`, adbParameters);
141}
142
8b383051Ruslan Bikkinin7 years ago143public parseSdkLocation(fileContent: string, logger?: ILogger) {
144const matches = fileContent.match(/^sdk\.dir=(.+)$/m);
145if (!matches || !matches[1]) {
146if (logger) {
d7d405aeYuri Skorokhodov7 years ago147logger.info(localize("NoSdkDirFoundInLocalPropertiesFile", "No sdk.dir value found in local.properties file. Using Android SDK location from PATH."));
8b383051Ruslan Bikkinin7 years ago148}
149return null;
150}
151
152let sdkLocation = matches[1].trim();
153if (os.platform() === "win32") {
154// For Windows we need to unescape files separators and drive letter separators
155sdkLocation = sdkLocation.replace(/\\\\/g, "\\").replace("\\:", ":");
156}
157if (logger) {
d7d405aeYuri Skorokhodov7 years ago158logger.info(localize("UsindAndroidSDKLocationDefinedInLocalPropertiesFile", "Using Android SDK location defined in android/local.properties file: {0}.", sdkLocation));
8b383051Ruslan Bikkinin7 years ago159}
160
161return sdkLocation;
162}
163
db6fd42aRuslan Bikkinin7 years ago164private parseConnectedDevices(input: string): IDevice[] {
52f3873ddigeff10 years ago165let result: IDevice[] = [];
166let regex = new RegExp("^(\\S+)\\t(\\S+)$", "mg");
167let match = regex.exec(input);
168while (match != null) {
169result.push({ id: match[1], isOnline: match[2] === "device", type: this.extractDeviceType(match[1]) });
170match = regex.exec(input);
171}
172return result;
173}
174
db6fd42aRuslan Bikkinin7 years ago175private extractDeviceType(id: string): DeviceType {
52f3873ddigeff10 years ago176return id.match(AndroidSDKEmulatorPattern)
177? DeviceType.AndroidSdkEmulator
178: DeviceType.Other;
179}
180
db6fd42aRuslan Bikkinin7 years ago181private executeQuery(deviceId: string, command: string): Q.Promise<string> {
52f3873ddigeff10 years ago182return this.childProcess.execToString(this.generateCommandForDevice(deviceId, command));
183}
184
db6fd42aRuslan Bikkinin7 years ago185private execute(deviceId: string, command: string): Q.Promise<void> {
52f3873ddigeff10 years ago186return this.commandExecutor.execute(this.generateCommandForDevice(deviceId, command));
187}
188
db6fd42aRuslan Bikkinin7 years ago189private generateCommandForDevice(deviceId: string, adbCommand: string): string {
190return `${this.adbExecutable} -s "${deviceId}" ${adbCommand}`;
191}
192
193private getSdkLocationFromLocalPropertiesFile(projectRoot: string, logger?: ILogger): string | null {
194const localPropertiesFilePath = path.join(projectRoot, "android", "local.properties");
195if (!fs.existsSync(localPropertiesFilePath)) {
196if (logger) {
d7d405aeYuri Skorokhodov7 years ago197logger.info(localize("LocalPropertiesFileDoesNotExist", "local.properties file doesn't exist. Using Android SDK location from PATH."));
db6fd42aRuslan Bikkinin7 years ago198}
199return null;
200}
201
8b383051Ruslan Bikkinin7 years ago202let fileContent: string;
db6fd42aRuslan Bikkinin7 years ago203try {
204fileContent = fs.readFileSync(localPropertiesFilePath).toString();
205} catch (e) {
206if (logger) {
d7d405aeYuri Skorokhodov7 years ago207logger.error(localize("CouldNotReadFrom", "Couldn't read from {0}.", localPropertiesFilePath), e, e.stack);
208logger.info(localize("UsingAndroidSDKLocationFromPATH", "Using Android SDK location from PATH."));
db6fd42aRuslan Bikkinin7 years ago209}
210return null;
211}
8b383051Ruslan Bikkinin7 years ago212return this.parseSdkLocation(fileContent, logger);
52f3873ddigeff10 years ago213}
214}