microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.6.3

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/android/androidPlatform.ts

235lines · 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> {
78return TelemetryHelper.generate("AndroidPlatform.runApp", () => {
8022afdfVladimir Kotikov8 years ago79const runArguments = this.getRunArgument();
1174ee3dArtem Egorov8 years ago80const env = this.getEnvArgument();
df8c800dArtem Egorov8 years ago81
82return ReactNativeProjectHelper.getReactNativeVersion(this.runOptions.projectRoot)
83.then(version => {
84if (semver.gte(version, AndroidPlatform.NO_PACKAGER_VERSION)) {
85runArguments.push("--no-packager");
52f3873ddigeff10 years ago86}
df8c800dArtem Egorov8 years ago87
1174ee3dArtem Egorov8 years ago88const runAndroidSpawn = new CommandExecutor(this.projectPath, this.logger).spawnReactCommand("run-android", runArguments, {env});
df8c800dArtem Egorov8 years ago89const output = new OutputVerifier(
90() =>
91Q(AndroidPlatform.RUN_ANDROID_SUCCESS_PATTERNS),
92() =>
93Q(AndroidPlatform.RUN_ANDROID_FAILURE_PATTERNS)).process(runAndroidSpawn);
94
95return output
96.finally(() => {
97return this.initializeTargetDevicesAndPackageName();
98}).then(() => [this.debugTarget], reason => {
99if (reason.message === AndroidPlatform.MULTIPLE_DEVICES_ERROR && this.devices.length > 1 && this.debugTarget) {
100/* If it failed due to multiple devices, we'll apply this workaround to make it work anyways */
101this.needsToLaunchApps = true;
102return shouldLaunchInAllDevices
103? AdbHelper.getOnlineDevices()
104: Q([this.debugTarget]);
105} else {
106return Q.reject<IDevice[]>(reason);
107}
108}).then(devices => {
109return new PromiseUtil().forEach(devices, device => {
110return this.launchAppWithADBReverseAndLogCat(device);
111});
112});
52f3873ddigeff10 years ago113});
114});
115}
116
117public enableJSDebuggingMode(): Q.Promise<void> {
7daed3fcArtem Egorov8 years ago118return AdbHelper.switchDebugMode(this.runOptions.projectRoot, this.packageName, true, this.debugTarget.id);
b57ea017Artem Egorov8 years ago119}
120
121public disableJSDebuggingMode(): Q.Promise<void> {
7daed3fcArtem Egorov8 years ago122return AdbHelper.switchDebugMode(this.runOptions.projectRoot, this.packageName, false, this.debugTarget.id);
52f3873ddigeff10 years ago123}
124
299b0557Patricio Beltran10 years ago125public prewarmBundleCache(): Q.Promise<void> {
0a68f8dbArtem Egorov8 years ago126return this.packager.prewarmBundleCache("android");
299b0557Patricio Beltran10 years ago127}
128
8022afdfVladimir Kotikov8 years ago129public getRunArgument(): string[] {
130let runArguments: string[] = [];
131
132if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) {
133runArguments = this.runOptions.runArguments;
134} else {
135if (this.runOptions.variant) {
136runArguments.push("--variant", this.runOptions.variant);
137}
138if (this.runOptions.target) {
139runArguments.push("--deviceId", this.runOptions.target);
140}
141}
142
143return runArguments;
144}
145
52f3873ddigeff10 years ago146private initializeTargetDevicesAndPackageName(): Q.Promise<void> {
7daed3fcArtem Egorov8 years ago147return AdbHelper.getConnectedDevices().then(devices => {
52f3873ddigeff10 years ago148this.devices = devices;
149this.debugTarget = this.getTargetEmulator(devices);
150return this.getPackageName().then(packageName => {
151this.packageName = packageName;
152});
153});
154}
155
156private launchAppWithADBReverseAndLogCat(device: IDevice): Q.Promise<void> {
157return Q({})
158.then(() => {
159return this.configureADBReverseWhenApplicable(device);
160}).then(() => {
161return this.needsToLaunchApps
7daed3fcArtem Egorov8 years ago162? AdbHelper.launchApp(this.runOptions.projectRoot, this.packageName, device.id)
52f3873ddigeff10 years ago163: Q<void>(void 0);
164}).then(() => {
0a68f8dbArtem Egorov8 years ago165return this.startMonitoringLogCat(device, this.runOptions.logCatArguments);
52f3873ddigeff10 years ago166});
167}
168
169private configureADBReverseWhenApplicable(device: IDevice): Q.Promise<void> {
b57ea017Artem Egorov8 years ago170return Q({}) // For other emulators and devices we try to enable adb reverse
7daed3fcArtem Egorov8 years ago171.then(() => AdbHelper.apiVersion(device.id))
b57ea017Artem Egorov8 years ago172.then(apiVersion => {
173if (apiVersion >= AndroidAPILevel.LOLLIPOP) { // If we support adb reverse
7daed3fcArtem Egorov8 years ago174return AdbHelper.reverseAdb(device.id, Number( this.runOptions.packagerPort));
b57ea017Artem Egorov8 years ago175} else {
0a68f8dbArtem Egorov8 years ago176this.logger.warning(`Device ${device.id} supports only API Level ${apiVersion}. `
b57ea017Artem Egorov8 years ago177+ `Level ${AndroidAPILevel.LOLLIPOP} is needed to support port forwarding via adb reverse. `
178+ "For debugging to work you'll need <Shake or press menu button> for the dev menu, "
179+ "go into <Dev Settings> and configure <Debug Server host & port for Device> to be "
180+ "an IP address of your computer that the Device can reach. More info at: "
181+ "https://facebook.github.io/react-native/docs/debugging.html#debugging-react-native-apps");
182return void 0;
183}
184});
52f3873ddigeff10 years ago185}
186
187private getPackageName(): Q.Promise<string> {
8022afdfVladimir Kotikov8 years ago188return new Package(this.runOptions.projectRoot).name().then(appName =>
52f3873ddigeff10 years ago189new PackageNameResolver(appName).resolvePackageName(this.runOptions.projectRoot));
190}
191
192/**
193* Returns the target emulator, using the following logic:
194* * If an emulator is specified and it is connected, use that one.
195* * Otherwise, use the first one in the list.
196*/
197private getTargetEmulator(devices: IDevice[]): IDevice {
198let activeFilterFunction = (device: IDevice) => {
199return device.isOnline;
200};
201
202let targetFilterFunction = (device: IDevice) => {
203return device.id === this.runOptions.target && activeFilterFunction(device);
204};
205
206if (this.runOptions && this.runOptions.target && devices) {
207/* check if the specified target is active */
208const targetDevice = devices.find(targetFilterFunction);
209if (targetDevice) {
210return targetDevice;
211}
212}
213
214/* return the first active device in the list */
215let activeDevices = devices && devices.filter(activeFilterFunction);
216return activeDevices && activeDevices[0];
217}
218
0a68f8dbArtem Egorov8 years ago219private startMonitoringLogCat(device: IDevice, logCatArguments: string): void {
220this.stopMonitoringLogCat(); // Stop previous logcat monitor if it's running
221
222// this.logCatMonitor can be mutated, so we store it locally too
223this.logCatMonitor = new LogCatMonitor(device.id, logCatArguments);
224this.logCatMonitor.start() // The LogCat will continue running forever, so we don't wait for it
225.catch(error => this.logger.warning("Error while monitoring LogCat", error)) // The LogCatMonitor failing won't stop the debugging experience
226.done();
227}
228
229private stopMonitoringLogCat(): void {
230if (this.logCatMonitor) {
231this.logCatMonitor.dispose();
232this.logCatMonitor = null;
233}
52f3873ddigeff10 years ago234}
ef902673Vladimir Kotikov9 years ago235}