microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/extension/android/androidPlatform.ts
243lines · 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 | |
| 4 | import * as Q from "q"; |
| 5 | import * as semver from "semver"; |
| 6 | |
| 7 | import {GeneralMobilePlatform, MobilePlatformDeps } from "../generalMobilePlatform"; |
| 8 | import {IAndroidRunOptions} from "../launchArgs"; |
| 9 | import {AdbHelper, AndroidAPILevel, IDevice} from "./adb"; |
| 10 | import {Package} from "../../common/node/package"; |
| 11 | import {PromiseUtil} from "../../common/node/promise"; |
| 12 | import {PackageNameResolver} from "./packageNameResolver"; |
| 13 | import {OutputVerifier, PatternToFailure} from "../../common/outputVerifier"; |
| 14 | import {TelemetryHelper} from "../../common/telemetryHelper"; |
| 15 | import {CommandExecutor} from "../../common/commandExecutor"; |
| 16 | import {LogCatMonitor} from "./logCatMonitor"; |
| 17 | import {ReactNativeProjectHelper} from "../../common/reactNativeProjectHelper"; |
| 18 | |
| 19 | /** |
| 20 | * Android specific platform implementation for debugging RN applications. |
| 21 | */ |
| 22 | export class AndroidPlatform extends GeneralMobilePlatform { |
| 23 | private static MULTIPLE_DEVICES_ERROR = "error: more than one device/emulator"; |
| 24 | |
| 25 | // We should add the common Android build/run errors we find to this list |
| 26 | private static RUN_ANDROID_FAILURE_PATTERNS: PatternToFailure[] = [{ |
| 27 | pattern: "Failed to install on any devices", |
| 28 | message: "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 | }, { |
| 31 | pattern: "com.android.ddmlib.ShellCommandUnresponsiveException", |
| 32 | message: "An Android shell command timed-out. Please retry the operation.", |
| 33 | }, { |
| 34 | pattern: "Android project not found", |
| 35 | message: "Android project not found.", |
| 36 | |
| 37 | }, { |
| 38 | pattern: "error: more than one device/emulator", |
| 39 | message: AndroidPlatform.MULTIPLE_DEVICES_ERROR, |
| 40 | }, { |
| 41 | pattern: /^Error: Activity class \{.*\} does not exist\.$/m, |
| 42 | message: "Failed to launch the specified activity. Try running application manually and " |
| 43 | + "start debugging using 'Attach to packager' launch configuration.", |
| 44 | }]; |
| 45 | |
| 46 | private static RUN_ANDROID_SUCCESS_PATTERNS: string[] = ["BUILD SUCCESSFUL", "Starting the app", "Starting: Intent"]; |
| 47 | |
| 48 | private debugTarget: IDevice; |
| 49 | private devices: IDevice[]; |
| 50 | private packageName: string; |
| 51 | private logCatMonitor: LogCatMonitor | null = null; |
| 52 | |
| 53 | private needsToLaunchApps: boolean = false; |
| 54 | public static showDevMenu(deviceId?: string): Q.Promise<void> { |
| 55 | return AdbHelper.showDevMenu(deviceId); |
| 56 | } |
| 57 | public static reloadApp(deviceId?: string): Q.Promise<void> { |
| 58 | return AdbHelper.reloadApp(deviceId); |
| 59 | } |
| 60 | |
| 61 | // 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. |
| 62 | constructor(protected runOptions: IAndroidRunOptions, platformDeps: MobilePlatformDeps = {}) { |
| 63 | super(runOptions, platformDeps); |
| 64 | |
| 65 | if (this.runOptions.target === AndroidPlatform.simulatorString || |
| 66 | this.runOptions.target === AndroidPlatform.deviceString) { |
| 67 | |
| 68 | const 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 | |
| 72 | this.logger.warning(message); |
| 73 | delete this.runOptions.target; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | public runApp(shouldLaunchInAllDevices: boolean = false): Q.Promise<void> { |
| 78 | const extProps = { |
| 79 | platform: { |
| 80 | value: "android", |
| 81 | isPii: false, |
| 82 | }, |
| 83 | }; |
| 84 | |
| 85 | return TelemetryHelper.generate("AndroidPlatform.runApp", extProps, () => { |
| 86 | const runArguments = this.getRunArgument(); |
| 87 | const env = this.getEnvArgument(); |
| 88 | |
| 89 | return ReactNativeProjectHelper.getReactNativeVersion(this.runOptions.projectRoot) |
| 90 | .then(version => { |
| 91 | if (!semver.valid(version) /*Custom RN implementations should support this flag*/ || semver.gte(version, AndroidPlatform.NO_PACKAGER_VERSION)) { |
| 92 | runArguments.push("--no-packager"); |
| 93 | } |
| 94 | |
| 95 | const runAndroidSpawn = new CommandExecutor(this.projectPath, this.logger).spawnReactCommand("run-android", runArguments, {env}); |
| 96 | const output = new OutputVerifier( |
| 97 | () => |
| 98 | Q(AndroidPlatform.RUN_ANDROID_SUCCESS_PATTERNS), |
| 99 | () => |
| 100 | Q(AndroidPlatform.RUN_ANDROID_FAILURE_PATTERNS), |
| 101 | "android").process(runAndroidSpawn); |
| 102 | |
| 103 | return output |
| 104 | .finally(() => { |
| 105 | return this.initializeTargetDevicesAndPackageName(); |
| 106 | }).then(() => [this.debugTarget], reason => { |
| 107 | if (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 */ |
| 109 | this.needsToLaunchApps = true; |
| 110 | return shouldLaunchInAllDevices |
| 111 | ? AdbHelper.getOnlineDevices() |
| 112 | : Q([this.debugTarget]); |
| 113 | } else { |
| 114 | return Q.reject<IDevice[]>(reason); |
| 115 | } |
| 116 | }).then(devices => { |
| 117 | return new PromiseUtil().forEach(devices, device => { |
| 118 | return this.launchAppWithADBReverseAndLogCat(device); |
| 119 | }); |
| 120 | }); |
| 121 | }); |
| 122 | }); |
| 123 | } |
| 124 | |
| 125 | public enableJSDebuggingMode(): Q.Promise<void> { |
| 126 | return AdbHelper.switchDebugMode(this.runOptions.projectRoot, this.packageName, true, this.debugTarget.id); |
| 127 | } |
| 128 | |
| 129 | public disableJSDebuggingMode(): Q.Promise<void> { |
| 130 | return AdbHelper.switchDebugMode(this.runOptions.projectRoot, this.packageName, false, this.debugTarget.id); |
| 131 | } |
| 132 | |
| 133 | public prewarmBundleCache(): Q.Promise<void> { |
| 134 | return this.packager.prewarmBundleCache("android"); |
| 135 | } |
| 136 | |
| 137 | public getRunArgument(): string[] { |
| 138 | let runArguments: string[] = []; |
| 139 | |
| 140 | if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) { |
| 141 | runArguments = this.runOptions.runArguments; |
| 142 | } else { |
| 143 | if (this.runOptions.variant) { |
| 144 | runArguments.push("--variant", this.runOptions.variant); |
| 145 | } |
| 146 | if (this.runOptions.target) { |
| 147 | runArguments.push("--deviceId", this.runOptions.target); |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | return runArguments; |
| 152 | } |
| 153 | |
| 154 | private initializeTargetDevicesAndPackageName(): Q.Promise<void> { |
| 155 | return AdbHelper.getConnectedDevices().then(devices => { |
| 156 | this.devices = devices; |
| 157 | this.debugTarget = this.getTargetEmulator(devices); |
| 158 | return this.getPackageName().then(packageName => { |
| 159 | this.packageName = packageName; |
| 160 | }); |
| 161 | }); |
| 162 | } |
| 163 | |
| 164 | private launchAppWithADBReverseAndLogCat(device: IDevice): Q.Promise<void> { |
| 165 | return Q({}) |
| 166 | .then(() => { |
| 167 | return this.configureADBReverseWhenApplicable(device); |
| 168 | }).then(() => { |
| 169 | return this.needsToLaunchApps |
| 170 | ? AdbHelper.launchApp(this.runOptions.projectRoot, this.packageName, device.id) |
| 171 | : Q<void>(void 0); |
| 172 | }).then(() => { |
| 173 | return this.startMonitoringLogCat(device, this.runOptions.logCatArguments); |
| 174 | }); |
| 175 | } |
| 176 | |
| 177 | private configureADBReverseWhenApplicable(device: IDevice): Q.Promise<void> { |
| 178 | return Q({}) // For other emulators and devices we try to enable adb reverse |
| 179 | .then(() => AdbHelper.apiVersion(device.id)) |
| 180 | .then(apiVersion => { |
| 181 | if (apiVersion >= AndroidAPILevel.LOLLIPOP) { // If we support adb reverse |
| 182 | return AdbHelper.reverseAdb(device.id, Number( this.runOptions.packagerPort)); |
| 183 | } else { |
| 184 | this.logger.warning(`Device ${device.id} supports only API Level ${apiVersion}. ` |
| 185 | + `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"); |
| 190 | return void 0; |
| 191 | } |
| 192 | }); |
| 193 | } |
| 194 | |
| 195 | private getPackageName(): Q.Promise<string> { |
| 196 | return new Package(this.runOptions.projectRoot).name().then(appName => |
| 197 | new 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 | */ |
| 205 | private getTargetEmulator(devices: IDevice[]): IDevice { |
| 206 | let activeFilterFunction = (device: IDevice) => { |
| 207 | return device.isOnline; |
| 208 | }; |
| 209 | |
| 210 | let targetFilterFunction = (device: IDevice) => { |
| 211 | return device.id === this.runOptions.target && activeFilterFunction(device); |
| 212 | }; |
| 213 | |
| 214 | if (this.runOptions && this.runOptions.target && devices) { |
| 215 | /* check if the specified target is active */ |
| 216 | const targetDevice = devices.find(targetFilterFunction); |
| 217 | if (targetDevice) { |
| 218 | return targetDevice; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /* return the first active device in the list */ |
| 223 | let activeDevices = devices && devices.filter(activeFilterFunction); |
| 224 | return activeDevices && activeDevices[0]; |
| 225 | } |
| 226 | |
| 227 | private startMonitoringLogCat(device: IDevice, logCatArguments: string): void { |
| 228 | this.stopMonitoringLogCat(); // Stop previous logcat monitor if it's running |
| 229 | |
| 230 | // this.logCatMonitor can be mutated, so we store it locally too |
| 231 | this.logCatMonitor = new LogCatMonitor(device.id, logCatArguments); |
| 232 | this.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 | |
| 237 | private stopMonitoringLogCat(): void { |
| 238 | if (this.logCatMonitor) { |
| 239 | this.logCatMonitor.dispose(); |
| 240 | this.logCatMonitor = null; |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |