import 'dart:async';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
import '../base/common.dart';
import '../base/context.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/os.dart';
import '../base/platform.dart';
import '../base/process_manager.dart';
import '../convert.dart';
import '../globals.dart';
ChromeLauncher get chromeLauncher => context.get<ChromeLauncher>();
const String kChromeEnvironment = 'CHROME_EXECUTABLE';
const String kLinuxExecutable = 'google-chrome';
const String kMacOSExecutable =
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const String kWindowsExecutable = r'Google\Chrome\Application\chrome.exe';
final List<String> kWindowsPrefixes = <String>[
platform.environment['LOCALAPPDATA'],
platform.environment['PROGRAMFILES'],
platform.environment['PROGRAMFILES(X86)']
];
String findChromeExecutable() {
if (platform.environment.containsKey(kChromeEnvironment)) {
return platform.environment[kChromeEnvironment];
}
if (platform.isLinux) {
return kLinuxExecutable;
}
if (platform.isMacOS) {
return kMacOSExecutable;
}
if (platform.isWindows) {
final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) {
if (prefix == null) {
return false;
}
final String path = fs.path.join(prefix, kWindowsExecutable);
return fs.file(path).existsSync();
}, orElse: () => '.');
return fs.path.join(windowsPrefix, kWindowsExecutable);
}
throwToolExit('Platform ${platform.operatingSystem} is not supported.');
return null;
}
class ChromeLauncher {
const ChromeLauncher();
static final Completer<Chrome> _currentCompleter = Completer<Chrome>();
Future<Chrome> launch(String url, { bool headless = false }) async {
final String chromeExecutable = findChromeExecutable();
final Directory dataDir = fs.systemTempDirectory.createTempSync();
final int port = await os.findFreePort();
final List<String> args = <String>[
chromeExecutable,
'--user-data-dir=${dataDir.path}',
'--remote-debugging-port=$port',
'--disable-background-timer-throttling',
'--disable-extensions',
'--disable-popup-blocking',
'--bwsi',
'--no-first-run',
'--no-default-browser-check',
'--disable-default-apps',
'--disable-translate',
if (headless)
...<String>['--headless', '--disable-gpu', '--no-sandbox'],
url,
];
final Process process = await processManager.start(args, runInShell: true);
await process.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.firstWhere((String line) => line.startsWith('DevTools listening'), orElse: () {
return 'Failed to spawn stderr';
})
.timeout(const Duration(seconds: 60), onTimeout: () {
throwToolExit('Unable to connect to Chrome DevTools.');
return null;
});
final Uri remoteDebuggerUri = await _getRemoteDebuggerUrl(Uri.parse('http://localhost:$port'));
return _connect(Chrome._(
port,
ChromeConnection('localhost', port),
process: process,
dataDir: dataDir,
remoteDebuggerUri: remoteDebuggerUri,
));
}
static Future<Chrome> _connect(Chrome chrome) async {
if (_currentCompleter.isCompleted) {
throwToolExit('Only one instance of chrome can be started.');
}
try {
await chrome.chromeConnection.getTabs();
} catch (e) {
await chrome.close();
throwToolExit(
'Unable to connect to Chrome debug port: ${chrome.debugPort}\n $e');
}
_currentCompleter.complete(chrome);
return chrome;
}
static Future<Chrome> fromExisting(int port) async =>
_connect(Chrome._(port, ChromeConnection('localhost', port)));
static Future<Chrome> get connectedInstance => _currentCompleter.future;
Future<Uri> _getRemoteDebuggerUrl(Uri base) async {
try {
final HttpClient client = HttpClient();
final HttpClientRequest request = await client.getUrl(base.resolve('/json/list'));
final HttpClientResponse response = await request.close();
final List<dynamic> jsonObject = await json.fuse(utf8).decoder.bind(response).single;
return base.resolve(jsonObject.first['devtoolsFrontendUrl']);
} catch (_) {
return base;
}
}
}
class Chrome {
Chrome._(
this.debugPort,
this.chromeConnection, {
Process process,
Directory dataDir,
this.remoteDebuggerUri,
}) : _process = process,
_dataDir = dataDir;
final int debugPort;
final Process _process;
final Directory _dataDir;
final ChromeConnection chromeConnection;
final Uri remoteDebuggerUri;
static Completer<Chrome> _currentCompleter = Completer<Chrome>();
Future<void> get onExit => _currentCompleter.future;
Future<void> close() async {
if (_currentCompleter.isCompleted) {
_currentCompleter = Completer<Chrome>();
}
chromeConnection.close();
_process?.kill();
await _process?.exitCode;
try {
await Future<void>.delayed(const Duration(milliseconds: 500));
} catch (_) {
} finally {
try {
await _dataDir?.delete(recursive: true);
} on FileSystemException {
printError('failed to delete temporary profile at ${_dataDir.path}');
}
}
}
}