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