microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/extension/android/adb.ts
336lines · modeblame
52f3873ddigeff10 years ago | 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. | |
| 3 | | |
db6fd42aRuslan Bikkinin7 years ago | 4 | import * as path from "path"; |
| 5 | import * as fs from "fs"; | |
8b383051Ruslan Bikkinin7 years ago | 6 | import * as os from "os"; |
d7d405aeYuri Skorokhodov7 years ago | 7 | import * as nls from "vscode-nls"; |
09f6024fHeniker4 years ago | 8 | import { ILogger } from "../log/LogHelper"; |
| 9 | import { CommandExecutor } from "../../common/commandExecutor"; | |
| 10 | import { ChildProcess, ISpawnResult } from "../../common/node/childProcess"; | |
0d77292aJiglioNero4 years ago | 11 | import { PromiseUtil } from "../../common/node/promise"; |
4cd25962JiglioNero4 years ago | 12 | import { IDebuggableMobileTarget } from "../mobileTarget"; |
09f6024fHeniker4 years ago | 13 | |
34472878RedMickey5 years ago | 14 | nls.config({ |
| 15 | messageFormat: nls.MessageFormat.bundle, | |
| 16 | bundleFormat: nls.BundleFormat.standalone, | |
| 17 | })(); | |
d7d405aeYuri Skorokhodov7 years ago | 18 | const localize = nls.loadMessageBundle(); |
52f3873ddigeff10 years ago | 19 | |
ce7fd946digeff10 years ago | 20 | // See android versions usage at: http://developer.android.com/about/dashboards/index.html |
52f3873ddigeff10 years ago | 21 | export enum AndroidAPILevel { |
ce7fd946digeff10 years ago | 22 | Marshmallow = 23, |
52f3873ddigeff10 years ago | 23 | LOLLIPOP_MR1 = 22, |
34472878RedMickey5 years ago | 24 | LOLLIPOP = 21 /* Supports adb reverse */, |
52f3873ddigeff10 years ago | 25 | KITKAT = 19, |
| 26 | JELLY_BEAN_MR2 = 18, | |
| 27 | JELLY_BEAN_MR1 = 17, | |
| 28 | JELLY_BEAN = 16, | |
| 29 | ICE_CREAM_SANDWICH_MR1 = 15, | |
| 30 | GINGERBREAD_MR1 = 10, | |
| 31 | } | |
| 32 | | |
7daed3fcArtem Egorov8 years ago | 33 | enum KeyEvents { |
| 34 | KEYCODE_BACK = 4, | |
| 35 | KEYCODE_DPAD_UP = 19, | |
| 36 | KEYCODE_DPAD_DOWN = 20, | |
| 37 | KEYCODE_DPAD_CENTER = 23, | |
| 38 | KEYCODE_MENU = 82, | |
| 39 | } | |
| 40 | | |
| 41 | export class AdbHelper { | |
4dfb1c4cetatanova5 years ago | 42 | private nodeModulesRoot: string; |
| 43 | private launchActivity: string; | |
db6fd42aRuslan Bikkinin7 years ago | 44 | private childProcess: ChildProcess = new ChildProcess(); |
4dfb1c4cetatanova5 years ago | 45 | private commandExecutor: CommandExecutor; |
db6fd42aRuslan Bikkinin7 years ago | 46 | private adbExecutable: string = ""; |
| 47 | | |
09f6024fHeniker4 years ago | 48 | private static readonly AndroidRemoteTargetPattern = |
| 49 | /^((?:\d{1,3}\.){3}\d{1,3}:\d{1,5}|.*_adb-tls-con{2}ect\._tcp.*)$/gm; | |
4cd25962JiglioNero4 years ago | 50 | public static readonly AndroidSDKEmulatorPattern = /^emulator-\d{1,5}$/; |
247f6e8cRedMickey5 years ago | 51 | |
4dfb1c4cetatanova5 years ago | 52 | constructor( |
| 53 | projectRoot: string, | |
| 54 | nodeModulesRoot: string, | |
| 55 | logger?: ILogger, | |
| 56 | launchActivity: string = "MainActivity", | |
| 57 | ) { | |
| 58 | this.nodeModulesRoot = nodeModulesRoot; | |
8152571aYuri Skorokhodov5 years ago | 59 | this.adbExecutable = this.getAdbPath(projectRoot, logger); |
4dfb1c4cetatanova5 years ago | 60 | this.commandExecutor = new CommandExecutor(this.nodeModulesRoot); |
78c2b4deRedMickey6 years ago | 61 | this.launchActivity = launchActivity; |
db6fd42aRuslan Bikkinin7 years ago | 62 | } |
52f3873ddigeff10 years ago | 63 | |
| 64 | /** | |
| 65 | * Gets the list of Android connected devices and emulators. | |
| 66 | */ | |
4cd25962JiglioNero4 years ago | 67 | public async getConnectedTargets(): Promise<IDebuggableMobileTarget[]> { |
0d77292aJiglioNero4 years ago | 68 | const output = await this.childProcess.execToString(`${this.adbExecutable} devices`); |
4cd25962JiglioNero4 years ago | 69 | return this.parseConnectedTargets(output); |
| 70 | } | |
| 71 | | |
| 72 | public async findOnlineTargetById( | |
| 73 | targetId: string, | |
| 74 | ): Promise<IDebuggableMobileTarget | undefined> { | |
| 75 | return (await this.getOnlineTargets()).find(target => target.id === targetId); | |
| 76 | } | |
| 77 | | |
| 78 | public async getAvdsNames(): Promise<string[]> { | |
| 79 | const res = await this.childProcess.execToString("emulator -list-avds"); | |
| 80 | let emulatorsNames: string[] = []; | |
| 81 | if (res) { | |
| 82 | emulatorsNames = res.split(/\r?\n|\r/g); | |
| 83 | const indexOfBlank = emulatorsNames.indexOf(""); | |
| 84 | if (indexOfBlank >= 0) { | |
| 85 | emulatorsNames.splice(indexOfBlank, 1); | |
| 86 | } | |
| 87 | } | |
| 88 | return emulatorsNames; | |
| 89 | } | |
| 90 | | |
| 91 | public isRemoteTarget(id: string): boolean { | |
| 92 | return !!id.match(AdbHelper.AndroidRemoteTargetPattern); | |
| 93 | } | |
| 94 | | |
| 95 | public async getAvdNameById(emulatorId: string): Promise<string | null> { | |
| 96 | try { | |
| 97 | const output = await this.childProcess.execToString( | |
| 98 | `${this.adbExecutable} -s ${emulatorId} emu avd name`, | |
| 99 | ); | |
| 100 | // The command returns the name of avd by id of this running emulator. | |
| 101 | // Return value example: | |
| 102 | // " | |
| 103 | // emuName | |
| 104 | // OK | |
| 105 | // " | |
09f6024fHeniker4 years ago | 106 | return output ? output.split(/\r?\n|\r/g)[0] : null; |
4cd25962JiglioNero4 years ago | 107 | } catch { |
| 108 | // If the command returned an error, it means that we could not find the emulator with the passed id | |
| 109 | return null; | |
| 110 | } | |
52f3873ddigeff10 years ago | 111 | } |
| 112 | | |
78c2b4deRedMickey6 years ago | 113 | public setLaunchActivity(launchActivity: string): void { |
| 114 | this.launchActivity = launchActivity; | |
| 115 | } | |
| 116 | | |
52f3873ddigeff10 years ago | 117 | /** |
| 118 | * Broadcasts an intent to reload the application in debug mode. | |
| 119 | */ | |
0d77292aJiglioNero4 years ago | 120 | public async switchDebugMode( |
34472878RedMickey5 years ago | 121 | projectRoot: string, |
| 122 | packageName: string, | |
| 123 | enable: boolean, | |
| 124 | debugTarget?: string, | |
69ad2ab3RedMickey5 years ago | 125 | appIdSuffix?: string, |
34472878RedMickey5 years ago | 126 | ): Promise<void> { |
09f6024fHeniker4 years ago | 127 | const enableDebugCommand = `${this.adbExecutable} ${ |
| 128 | debugTarget ? `-s ${debugTarget}` : "" | |
| 129 | } shell am broadcast -a "${packageName}.RELOAD_APP_ACTION" --ez jsproxy ${String(enable)}`; | |
0d77292aJiglioNero4 years ago | 130 | await new CommandExecutor(this.nodeModulesRoot, projectRoot).execute(enableDebugCommand); |
| 131 | // We should stop and start application again after RELOAD_APP_ACTION, otherwise app going to hangs up | |
| 132 | await PromiseUtil.delay(200); // We need a little delay after broadcast command | |
| 133 | await this.stopApp(projectRoot, packageName, debugTarget, appIdSuffix); | |
| 134 | return this.launchApp(projectRoot, packageName, debugTarget, appIdSuffix); | |
52f3873ddigeff10 years ago | 135 | } |
| 136 | | |
| 137 | /** | |
| 138 | * Sends an intent which launches the main activity of the application. | |
| 139 | */ | |
34472878RedMickey5 years ago | 140 | public launchApp( |
| 141 | projectRoot: string, | |
| 142 | packageName: string, | |
| 143 | debugTarget?: string, | |
69ad2ab3RedMickey5 years ago | 144 | appIdSuffix?: string, |
34472878RedMickey5 years ago | 145 | ): Promise<void> { |
09f6024fHeniker4 years ago | 146 | const launchAppCommand = `${this.adbExecutable} ${ |
| 147 | debugTarget ? `-s ${debugTarget}` : "" | |
| 148 | } shell am start -n ${packageName}${appIdSuffix ? `.${appIdSuffix}` : ""}/${packageName}.${ | |
69ad2ab3RedMickey5 years ago | 149 | this.launchActivity |
| 150 | }`; | |
52f3873ddigeff10 years ago | 151 | return new CommandExecutor(projectRoot).execute(launchAppCommand); |
| 152 | } | |
| 153 | | |
69ad2ab3RedMickey5 years ago | 154 | public stopApp( |
| 155 | projectRoot: string, | |
| 156 | packageName: string, | |
| 157 | debugTarget?: string, | |
| 158 | appIdSuffix?: string, | |
| 159 | ): Promise<void> { | |
09f6024fHeniker4 years ago | 160 | const stopAppCommand = `${this.adbExecutable} ${ |
| 161 | debugTarget ? `-s ${debugTarget}` : "" | |
| 162 | } shell am force-stop ${packageName}${appIdSuffix ? `.${appIdSuffix}` : ""}`; | |
b57ea017Artem Egorov8 years ago | 163 | return new CommandExecutor(projectRoot).execute(stopAppCommand); |
| 164 | } | |
| 165 | | |
0d77292aJiglioNero4 years ago | 166 | public async apiVersion(deviceId: string): Promise<AndroidAPILevel> { |
| 167 | const output = await this.executeQuery(deviceId, "shell getprop ro.build.version.sdk"); | |
| 168 | return parseInt(output, 10); | |
52f3873ddigeff10 years ago | 169 | } |
| 170 | | |
4bb0956eRedMickey5 years ago | 171 | public reverseAdb(deviceId: string, port: number): Promise<void> { |
| 172 | return this.execute(deviceId, `reverse tcp:${port} tcp:${port}`); | |
52f3873ddigeff10 years ago | 173 | } |
| 174 | | |
ce5e88eeYuri Skorokhodov5 years ago | 175 | public showDevMenu(deviceId?: string): Promise<void> { |
09f6024fHeniker4 years ago | 176 | const command = `${this.adbExecutable} ${ |
| 177 | deviceId ? `-s ${deviceId}` : "" | |
34472878RedMickey5 years ago | 178 | } shell input keyevent ${KeyEvents.KEYCODE_MENU}`; |
7daed3fcArtem Egorov8 years ago | 179 | return this.commandExecutor.execute(command); |
| 180 | } | |
| 181 | | |
ce5e88eeYuri Skorokhodov5 years ago | 182 | public reloadApp(deviceId?: string): Promise<void> { |
09f6024fHeniker4 years ago | 183 | const command = `${this.adbExecutable} ${ |
| 184 | deviceId ? `-s ${deviceId}` : "" | |
34472878RedMickey5 years ago | 185 | } shell input text "RR"`; |
e23ea82cAlter Code7 years ago | 186 | return this.commandExecutor.execute(command); |
7daed3fcArtem Egorov8 years ago | 187 | } |
| 188 | | |
4cd25962JiglioNero4 years ago | 189 | public async getOnlineTargets(): Promise<IDebuggableMobileTarget[]> { |
| 190 | const devices = await this.getConnectedTargets(); | |
0d77292aJiglioNero4 years ago | 191 | return devices.filter(device => device.isOnline); |
7daed3fcArtem Egorov8 years ago | 192 | } |
| 193 | | |
db6fd42aRuslan Bikkinin7 years ago | 194 | public startLogCat(adbParameters: string[]): ISpawnResult { |
09f6024fHeniker4 years ago | 195 | return this.childProcess.spawn(this.adbExecutable.replace(/"/g, ""), adbParameters); |
db6fd42aRuslan Bikkinin7 years ago | 196 | } |
| 197 | | |
8df5011eYuri Skorokhodov5 years ago | 198 | public parseSdkLocation(fileContent: string, logger?: ILogger): string | null { |
1864d974RedMickey4 years ago | 199 | const matches = fileContent.match(/^sdk\.dir\s*=(.+)$/m); |
8b383051Ruslan Bikkinin7 years ago | 200 | if (!matches || !matches[1]) { |
| 201 | if (logger) { | |
34472878RedMickey5 years ago | 202 | logger.info( |
| 203 | localize( | |
| 204 | "NoSdkDirFoundInLocalPropertiesFile", | |
| 205 | "No sdk.dir value found in local.properties file. Using Android SDK location from PATH.", | |
| 206 | ), | |
| 207 | ); | |
8b383051Ruslan Bikkinin7 years ago | 208 | } |
| 209 | return null; | |
| 210 | } | |
| 211 | | |
| 212 | let sdkLocation = matches[1].trim(); | |
| 213 | if (os.platform() === "win32") { | |
| 214 | // For Windows we need to unescape files separators and drive letter separators | |
| 215 | sdkLocation = sdkLocation.replace(/\\\\/g, "\\").replace("\\:", ":"); | |
| 216 | } | |
| 217 | if (logger) { | |
34472878RedMickey5 years ago | 218 | logger.info( |
| 219 | localize( | |
| 220 | "UsindAndroidSDKLocationDefinedInLocalPropertiesFile", | |
| 221 | "Using Android SDK location defined in android/local.properties file: {0}.", | |
| 222 | sdkLocation, | |
| 223 | ), | |
| 224 | ); | |
8b383051Ruslan Bikkinin7 years ago | 225 | } |
| 226 | | |
| 227 | return sdkLocation; | |
| 228 | } | |
| 229 | | |
8152571aYuri Skorokhodov5 years ago | 230 | public getAdbPath(projectRoot: string, logger?: ILogger): string { |
| 231 | const sdkLocation = this.getSdkLocationFromLocalPropertiesFile(projectRoot, logger); | |
e4e4820aEzio Li3 years ago | 232 | if (sdkLocation) { |
| 233 | const localPropertiesSdkPath = path.join( | |
| 234 | sdkLocation as string, | |
| 235 | "platform-tools", | |
| 236 | os.platform() === "win32" ? "adb.exe" : "adb", | |
| 237 | ); | |
| 238 | const isExist = fs.existsSync(localPropertiesSdkPath); | |
| 239 | if (isExist) { | |
79e49c88Gradyn Wursten2 years ago | 240 | return `"${localPropertiesSdkPath}"`; |
e4e4820aEzio Li3 years ago | 241 | } |
| 242 | if (logger) { | |
| 243 | logger.warning( | |
| 244 | localize( | |
| 245 | "LocalPropertiesAndroidSDKPathNotExistingInLocal", | |
| 246 | "Local.properties file has Andriod SDK path but cannot find it in your local, will switch to SDK PATH in environment variable. Please check Android SDK path in android/local.properties file.", | |
| 247 | ), | |
| 248 | ); | |
| 249 | } | |
| 250 | return "adb"; | |
| 251 | } | |
| 252 | return "adb"; | |
8152571aYuri Skorokhodov5 years ago | 253 | } |
| 254 | | |
4bb0956eRedMickey5 years ago | 255 | public executeShellCommand(deviceId: string, command: string): Promise<string> { |
| 256 | return this.executeQuery(deviceId, `shell "${command}"`); | |
| 257 | } | |
| 258 | | |
2a485fd5Ezio Li2 years ago | 259 | public installApplicationToEmulator(appPath: string): Promise<string> { |
| 260 | return this.childProcess.execToString(`adb install ${appPath}`); | |
| 261 | } | |
| 262 | | |
4bb0956eRedMickey5 years ago | 263 | public executeQuery(deviceId: string, command: string): Promise<string> { |
4cd25962JiglioNero4 years ago | 264 | return this.childProcess.execToString(this.generateCommandForTarget(deviceId, command)); |
4bb0956eRedMickey5 years ago | 265 | } |
| 266 | | |
4cd25962JiglioNero4 years ago | 267 | private parseConnectedTargets(input: string): IDebuggableMobileTarget[] { |
09f6024fHeniker4 years ago | 268 | const result: IDebuggableMobileTarget[] = []; |
| 269 | const regex = new RegExp("^(\\S+)\\t(\\S+)$", "mg"); | |
52f3873ddigeff10 years ago | 270 | let match = regex.exec(input); |
| 271 | while (match != null) { | |
34472878RedMickey5 years ago | 272 | result.push({ |
| 273 | id: match[1], | |
| 274 | isOnline: match[2] === "device", | |
4cd25962JiglioNero4 years ago | 275 | isVirtualTarget: this.isVirtualTarget(match[1]), |
34472878RedMickey5 years ago | 276 | }); |
52f3873ddigeff10 years ago | 277 | match = regex.exec(input); |
| 278 | } | |
| 279 | return result; | |
| 280 | } | |
| 281 | | |
4cd25962JiglioNero4 years ago | 282 | public isVirtualTarget(id: string): boolean { |
| 283 | return !!id.match(AdbHelper.AndroidSDKEmulatorPattern); | |
52f3873ddigeff10 years ago | 284 | } |
| 285 | | |
ce5e88eeYuri Skorokhodov5 years ago | 286 | private execute(deviceId: string, command: string): Promise<void> { |
4cd25962JiglioNero4 years ago | 287 | return this.commandExecutor.execute(this.generateCommandForTarget(deviceId, command)); |
52f3873ddigeff10 years ago | 288 | } |
| 289 | | |
4cd25962JiglioNero4 years ago | 290 | private generateCommandForTarget(deviceId: string, adbCommand: string): string { |
db6fd42aRuslan Bikkinin7 years ago | 291 | return `${this.adbExecutable} -s "${deviceId}" ${adbCommand}`; |
| 292 | } | |
| 293 | | |
34472878RedMickey5 years ago | 294 | private getSdkLocationFromLocalPropertiesFile( |
| 295 | projectRoot: string, | |
| 296 | logger?: ILogger, | |
| 297 | ): string | null { | |
db6fd42aRuslan Bikkinin7 years ago | 298 | const localPropertiesFilePath = path.join(projectRoot, "android", "local.properties"); |
| 299 | if (!fs.existsSync(localPropertiesFilePath)) { | |
| 300 | if (logger) { | |
34472878RedMickey5 years ago | 301 | logger.info( |
| 302 | localize( | |
| 303 | "LocalPropertiesFileDoesNotExist", | |
| 304 | "local.properties file doesn't exist. Using Android SDK location from PATH.", | |
| 305 | ), | |
| 306 | ); | |
db6fd42aRuslan Bikkinin7 years ago | 307 | } |
| 308 | return null; | |
| 309 | } | |
| 310 | | |
8b383051Ruslan Bikkinin7 years ago | 311 | let fileContent: string; |
db6fd42aRuslan Bikkinin7 years ago | 312 | try { |
| 313 | fileContent = fs.readFileSync(localPropertiesFilePath).toString(); | |
| 314 | } catch (e) { | |
| 315 | if (logger) { | |
34472878RedMickey5 years ago | 316 | logger.error( |
| 317 | localize( | |
| 318 | "CouldNotReadFrom", | |
| 319 | "Couldn't read from {0}.", | |
| 320 | localPropertiesFilePath, | |
| 321 | ), | |
| 322 | e, | |
| 323 | e.stack, | |
| 324 | ); | |
| 325 | logger.info( | |
| 326 | localize( | |
| 327 | "UsingAndroidSDKLocationFromPATH", | |
| 328 | "Using Android SDK location from PATH.", | |
| 329 | ), | |
| 330 | ); | |
db6fd42aRuslan Bikkinin7 years ago | 331 | } |
| 332 | return null; | |
| 333 | } | |
8b383051Ruslan Bikkinin7 years ago | 334 | return this.parseSdkLocation(fileContent, logger); |
52f3873ddigeff10 years ago | 335 | } |
| 336 | } |