From bd05889f1ff9ff60f5bde8ebd7c2dc871b2b9b59 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Thu, 1 Apr 2021 10:51:27 -0700 Subject: [PATCH] Activate android emulator window (#3345) * Activate android emulator window * Update Android.ts --- packages/xdl/src/Android.ts | 45 ++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/packages/xdl/src/Android.ts b/packages/xdl/src/Android.ts index 7c16830fce..de9d7d0ff0 100644 --- a/packages/xdl/src/Android.ts +++ b/packages/xdl/src/Android.ts @@ -1,5 +1,6 @@ import { ExpoConfig, getConfig, readExpRcAsync } from '@expo/config'; import { AndroidConfig } from '@expo/config-plugins'; +import * as osascript from '@expo/osascript'; import spawnAsync from '@expo/spawn-async'; import chalk from 'chalk'; import child_process, { execFileSync } from 'child_process'; @@ -551,8 +552,45 @@ async function _openUrlAsync({ return openProject; } +function getUnixPID(port: number | string) { + return execFileSync('lsof', [`-i:${port}`, '-P', '-t', '-sTCP:LISTEN'], { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'ignore'], + }) + .split('\n')[0] + .trim(); +} + +export async function activateEmulatorWindowAsync(device: Pick) { + if ( + // only mac is supported for now. + process.platform !== 'darwin' || + // can only focus emulators + device.type !== 'emulator' + ) { + return; + } + + // Google Emulator ID: `emulator-5554` -> `5554` + const androidPid = device.pid!.match(/-(\d+)/)?.[1]; + if (!androidPid) { + return; + } + // Unix PID + const pid = getUnixPID(androidPid); + + try { + await osascript.execAsync(` + tell application "System Events" + set frontmost of the first process whose unix id is ${pid} to true + end tell`); + } catch { + // noop -- this feature is very specific and subject to failure. + } +} + export async function openAppAsync( - device: Pick, + device: Pick, { packageName, mainActivity, @@ -583,6 +621,8 @@ export async function openAppAsync( throw new Error(openProject.substring(openProject.indexOf('Error: '))); } + await activateEmulatorWindowAsync(device); + return openProject; } @@ -635,6 +675,9 @@ async function openUrlAsync({ if (!bootedDevice) { return; } + + await activateEmulatorWindowAsync(bootedDevice); + device = bootedDevice; let installedExpo = false;