microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.6.12

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/android/androidPlatform.ts

243lines · 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";
df8c800dArtem Egorov8 years ago5import * as semver from "semver";
52f3873ddigeff10 years ago6
5c8365a6Artem Egorov8 years ago7import {GeneralMobilePlatform, MobilePlatformDeps } from "../generalMobilePlatform";
0db0be15Artem Egorov8 years ago8import {IAndroidRunOptions} from "../launchArgs";
7daed3fcArtem Egorov8 years ago9import {AdbHelper, AndroidAPILevel, IDevice} from "./adb";
0a68f8dbArtem Egorov8 years ago10import {Package} from "../../common/node/package";
11import {PromiseUtil} from "../../common/node/promise";
5c8365a6Artem Egorov8 years ago12import {PackageNameResolver} from "./packageNameResolver";
0a68f8dbArtem Egorov8 years ago13import {OutputVerifier, PatternToFailure} from "../../common/outputVerifier";
14import {TelemetryHelper} from "../../common/telemetryHelper";
8022afdfVladimir Kotikov8 years ago15import {CommandExecutor} from "../../common/commandExecutor";
0a68f8dbArtem Egorov8 years ago16import {LogCatMonitor} from "./logCatMonitor";
df8c800dArtem Egorov8 years ago17import {ReactNativeProjectHelper} from "../../common/reactNativeProjectHelper";
5c8365a6Artem Egorov8 years ago18
52f3873ddigeff10 years ago19/**
20* Android specific platform implementation for debugging RN applications.
21*/
299b0557Patricio Beltran10 years ago22export class AndroidPlatform extends GeneralMobilePlatform {
52f3873ddigeff10 years ago23private static MULTIPLE_DEVICES_ERROR = "error: more than one device/emulator";
24
0a68f8dbArtem Egorov8 years ago25// We should add the common Android build/run errors we find to this list
ef902673Vladimir Kotikov9 years ago26private static RUN_ANDROID_FAILURE_PATTERNS: PatternToFailure[] = [{
27pattern: "Failed to install on any devices",
28message: "Could not install the app on any available device. Make sure you have a correctly"
29+ " configured device or emulator running. See https://facebook.github.io/react-native/docs/android-setup.html",
30}, {
31pattern: "com.android.ddmlib.ShellCommandUnresponsiveException",
32message: "An Android shell command timed-out. Please retry the operation.",
33}, {
34pattern: "Android project not found",
35message: "Android project not found.",
36
37}, {
38pattern: "error: more than one device/emulator",
39message: AndroidPlatform.MULTIPLE_DEVICES_ERROR,
40}, {
41pattern: /^Error: Activity class \{.*\} does not exist\.$/m,
42message: "Failed to launch the specified activity. Try running application manually and "
43+ "start debugging using 'Attach to packager' launch configuration.",
44}];
52f3873ddigeff10 years ago45
46private static RUN_ANDROID_SUCCESS_PATTERNS: string[] = ["BUILD SUCCESSFUL", "Starting the app", "Starting: Intent"];
47
48private debugTarget: IDevice;
49private devices: IDevice[];
50private packageName: string;
0a68f8dbArtem Egorov8 years ago51private logCatMonitor: LogCatMonitor | null = null;
52f3873ddigeff10 years ago52
53private needsToLaunchApps: boolean = false;
7daed3fcArtem Egorov8 years ago54public static showDevMenu(deviceId?: string): Q.Promise<void> {
55return AdbHelper.showDevMenu(deviceId);
56}
57public static reloadApp(deviceId?: string): Q.Promise<void> {
58return AdbHelper.reloadApp(deviceId);
59}
52f3873ddigeff10 years ago60
299b0557Patricio Beltran10 years ago61// We set remoteExtension = null so that if there is an instance of androidPlatform that wants to have it's custom remoteExtension it can. This is specifically useful for tests.
7daed3fcArtem Egorov8 years ago62constructor(protected runOptions: IAndroidRunOptions, platformDeps: MobilePlatformDeps = {}) {
0a68f8dbArtem Egorov8 years ago63super(runOptions, platformDeps);
1ca47c7cArtem Egorov8 years ago64
65if (this.runOptions.target === AndroidPlatform.simulatorString ||
66this.runOptions.target === AndroidPlatform.deviceString) {
67
68const message = `Target ${this.runOptions.target} is not supported for Android ` +
69"platform. If you want to use particular device or simulator for launching " +
70"Android app, please specify device id (as in 'adb devices' output) instead.";
71
0a68f8dbArtem Egorov8 years ago72this.logger.warning(message);
1ca47c7cArtem Egorov8 years ago73delete this.runOptions.target;
74}
52f3873ddigeff10 years ago75}
76
77public runApp(shouldLaunchInAllDevices: boolean = false): Q.Promise<void> {
031832ffArtem Egorov8 years ago78const extProps = {
79platform: {
80value: "android",
81isPii: false,
82},
83};
84
85return TelemetryHelper.generate("AndroidPlatform.runApp", extProps, () => {
8022afdfVladimir Kotikov8 years ago86const runArguments = this.getRunArgument();
1174ee3dArtem Egorov8 years ago87const env = this.getEnvArgument();
df8c800dArtem Egorov8 years ago88
89return ReactNativeProjectHelper.getReactNativeVersion(this.runOptions.projectRoot)
90.then(version => {
6786e358Artem Egorov8 years ago91if (!semver.valid(version) /*Custom RN implementations should support this flag*/ || semver.gte(version, AndroidPlatform.NO_PACKAGER_VERSION)) {
df8c800dArtem Egorov8 years ago92runArguments.push("--no-packager");
52f3873ddigeff10 years ago93}
df8c800dArtem Egorov8 years ago94
1174ee3dArtem Egorov8 years ago95const runAndroidSpawn = new CommandExecutor(this.projectPath, this.logger).spawnReactCommand("run-android", runArguments, {env});
df8c800dArtem Egorov8 years ago96const output = new OutputVerifier(
97() =>
98Q(AndroidPlatform.RUN_ANDROID_SUCCESS_PATTERNS),
99() =>
77a9922aRuslan Bikkinin8 years ago100Q(AndroidPlatform.RUN_ANDROID_FAILURE_PATTERNS),
101"android").process(runAndroidSpawn);
df8c800dArtem Egorov8 years ago102
103return output
104.finally(() => {
105return this.initializeTargetDevicesAndPackageName();
106}).then(() => [this.debugTarget], reason => {
107if (reason.message === AndroidPlatform.MULTIPLE_DEVICES_ERROR && this.devices.length > 1 && this.debugTarget) {
108/* If it failed due to multiple devices, we'll apply this workaround to make it work anyways */
109this.needsToLaunchApps = true;
110return shouldLaunchInAllDevices
111? AdbHelper.getOnlineDevices()
112: Q([this.debugTarget]);
113} else {
114return Q.reject<IDevice[]>(reason);
115}
116}).then(devices => {
117return new PromiseUtil().forEach(devices, device => {
118return this.launchAppWithADBReverseAndLogCat(device);
119});
120});
52f3873ddigeff10 years ago121});
122});
123}
124
125public enableJSDebuggingMode(): Q.Promise<void> {
7daed3fcArtem Egorov8 years ago126return AdbHelper.switchDebugMode(this.runOptions.projectRoot, this.packageName, true, this.debugTarget.id);
b57ea017Artem Egorov8 years ago127}
128
129public disableJSDebuggingMode(): Q.Promise<void> {
7daed3fcArtem Egorov8 years ago130return AdbHelper.switchDebugMode(this.runOptions.projectRoot, this.packageName, false, this.debugTarget.id);
52f3873ddigeff10 years ago131}
132
299b0557Patricio Beltran10 years ago133public prewarmBundleCache(): Q.Promise<void> {
0a68f8dbArtem Egorov8 years ago134return this.packager.prewarmBundleCache("android");
299b0557Patricio Beltran10 years ago135}
136
8022afdfVladimir Kotikov8 years ago137public getRunArgument(): string[] {
138let runArguments: string[] = [];
139
140if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) {
141runArguments = this.runOptions.runArguments;
142} else {
143if (this.runOptions.variant) {
144runArguments.push("--variant", this.runOptions.variant);
145}
146if (this.runOptions.target) {
147runArguments.push("--deviceId", this.runOptions.target);
148}
149}
150
151return runArguments;
152}
153
52f3873ddigeff10 years ago154private initializeTargetDevicesAndPackageName(): Q.Promise<void> {
7daed3fcArtem Egorov8 years ago155return AdbHelper.getConnectedDevices().then(devices => {
52f3873ddigeff10 years ago156this.devices = devices;
157this.debugTarget = this.getTargetEmulator(devices);
158return this.getPackageName().then(packageName => {
159this.packageName = packageName;
160});
161});
162}
163
164private launchAppWithADBReverseAndLogCat(device: IDevice): Q.Promise<void> {
165return Q({})
166.then(() => {
167return this.configureADBReverseWhenApplicable(device);
168}).then(() => {
169return this.needsToLaunchApps
7daed3fcArtem Egorov8 years ago170? AdbHelper.launchApp(this.runOptions.projectRoot, this.packageName, device.id)
52f3873ddigeff10 years ago171: Q<void>(void 0);
172}).then(() => {
0a68f8dbArtem Egorov8 years ago173return this.startMonitoringLogCat(device, this.runOptions.logCatArguments);
52f3873ddigeff10 years ago174});
175}
176
177private configureADBReverseWhenApplicable(device: IDevice): Q.Promise<void> {
b57ea017Artem Egorov8 years ago178return Q({}) // For other emulators and devices we try to enable adb reverse
7daed3fcArtem Egorov8 years ago179.then(() => AdbHelper.apiVersion(device.id))
b57ea017Artem Egorov8 years ago180.then(apiVersion => {
181if (apiVersion >= AndroidAPILevel.LOLLIPOP) { // If we support adb reverse
7daed3fcArtem Egorov8 years ago182return AdbHelper.reverseAdb(device.id, Number( this.runOptions.packagerPort));
b57ea017Artem Egorov8 years ago183} else {
0a68f8dbArtem Egorov8 years ago184this.logger.warning(`Device ${device.id} supports only API Level ${apiVersion}. `
b57ea017Artem Egorov8 years ago185+ `Level ${AndroidAPILevel.LOLLIPOP} is needed to support port forwarding via adb reverse. `
186+ "For debugging to work you'll need <Shake or press menu button> for the dev menu, "
187+ "go into <Dev Settings> and configure <Debug Server host & port for Device> to be "
188+ "an IP address of your computer that the Device can reach. More info at: "
189+ "https://facebook.github.io/react-native/docs/debugging.html#debugging-react-native-apps");
190return void 0;
191}
192});
52f3873ddigeff10 years ago193}
194
195private getPackageName(): Q.Promise<string> {
8022afdfVladimir Kotikov8 years ago196return new Package(this.runOptions.projectRoot).name().then(appName =>
52f3873ddigeff10 years ago197new PackageNameResolver(appName).resolvePackageName(this.runOptions.projectRoot));
198}
199
200/**
201* Returns the target emulator, using the following logic:
202* * If an emulator is specified and it is connected, use that one.
203* * Otherwise, use the first one in the list.
204*/
205private getTargetEmulator(devices: IDevice[]): IDevice {
206let activeFilterFunction = (device: IDevice) => {
207return device.isOnline;
208};
209
210let targetFilterFunction = (device: IDevice) => {
211return device.id === this.runOptions.target && activeFilterFunction(device);
212};
213
214if (this.runOptions && this.runOptions.target && devices) {
215/* check if the specified target is active */
216const targetDevice = devices.find(targetFilterFunction);
217if (targetDevice) {
218return targetDevice;
219}
220}
221
222/* return the first active device in the list */
223let activeDevices = devices && devices.filter(activeFilterFunction);
224return activeDevices && activeDevices[0];
225}
226
0a68f8dbArtem Egorov8 years ago227private startMonitoringLogCat(device: IDevice, logCatArguments: string): void {
228this.stopMonitoringLogCat(); // Stop previous logcat monitor if it's running
229
230// this.logCatMonitor can be mutated, so we store it locally too
231this.logCatMonitor = new LogCatMonitor(device.id, logCatArguments);
232this.logCatMonitor.start() // The LogCat will continue running forever, so we don't wait for it
233.catch(error => this.logger.warning("Error while monitoring LogCat", error)) // The LogCatMonitor failing won't stop the debugging experience
234.done();
235}
236
237private stopMonitoringLogCat(): void {
238if (this.logCatMonitor) {
239this.logCatMonitor.dispose();
240this.logCatMonitor = null;
241}
52f3873ddigeff10 years ago242}
ef902673Vladimir Kotikov9 years ago243}