android_emulator.dart 7.92 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:meta/meta.dart';
8
import 'package:process/process.dart';
9

10
import '../base/file_system.dart';
Dan Field's avatar
Dan Field committed
11
import '../base/io.dart';
12
import '../base/logger.dart';
13
import '../base/process.dart';
Dan Field's avatar
Dan Field committed
14
import '../convert.dart';
15
import '../device.dart';
16 17
import '../emulator.dart';
import 'android_sdk.dart';
18
import 'android_workflow.dart';
19 20

class AndroidEmulators extends EmulatorDiscovery {
21
  AndroidEmulators({
22 23 24 25 26
    AndroidSdk? androidSdk,
    required AndroidWorkflow androidWorkflow,
    required FileSystem fileSystem,
    required Logger logger,
    required ProcessManager processManager,
27 28 29 30 31 32 33 34
  }) : _androidSdk = androidSdk,
       _androidWorkflow = androidWorkflow,
       _fileSystem = fileSystem,
       _logger = logger,
       _processManager = processManager,
       _processUtils = ProcessUtils(logger: logger, processManager: processManager);

  final AndroidWorkflow _androidWorkflow;
35
  final AndroidSdk? _androidSdk;
36 37 38 39 40
  final FileSystem _fileSystem;
  final Logger _logger;
  final ProcessManager _processManager;
  final ProcessUtils _processUtils;

41 42 43 44
  @override
  bool get supportsPlatform => true;

  @override
45 46 47 48
  bool get canListAnything => _androidWorkflow.canListEmulators;

  @override
  bool get canLaunchAnything => _androidWorkflow.canListEmulators
49
    && _androidSdk?.getAvdManagerPath() != null;
50 51

  @override
52 53 54 55
  Future<List<Emulator>> get emulators => _getEmulatorAvds();

  /// Return the list of available emulator AVDs.
  Future<List<AndroidEmulator>> _getEmulatorAvds() async {
56
    final String? emulatorPath = _androidSdk?.emulatorPath;
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    if (emulatorPath == null) {
      return <AndroidEmulator>[];
    }

    final String listAvdsOutput = (await _processUtils.run(
      <String>[emulatorPath, '-list-avds'])).stdout.trim();

    final List<AndroidEmulator> emulators = <AndroidEmulator>[];
    if (listAvdsOutput != null) {
      _extractEmulatorAvdInfo(listAvdsOutput, emulators);
    }
    return emulators;
  }

  /// Parse the given `emulator -list-avds` output in [text], and fill out the given list
  /// of emulators by reading information from the relevant ini files.
  void _extractEmulatorAvdInfo(String text, List<AndroidEmulator> emulators) {
    for (final String id in text.trim().split('\n').where((String l) => l != '')) {
      emulators.add(_loadEmulatorInfo(id));
    }
  }

  AndroidEmulator _loadEmulatorInfo(String id) {
    id = id.trim();
81
    final String? avdPath = _androidSdk?.getAvdPath();
82 83 84 85 86 87 88 89 90 91 92 93 94 95
    final AndroidEmulator androidEmulatorWithoutProperties = AndroidEmulator(
      id,
      processManager: _processManager,
      logger: _logger,
      androidSdk: _androidSdk,
    );
    if (avdPath == null) {
      return androidEmulatorWithoutProperties;
    }
    final File iniFile = _fileSystem.file(_fileSystem.path.join(avdPath, '$id.ini'));
    if (!iniFile.existsSync()) {
      return androidEmulatorWithoutProperties;
    }
    final Map<String, String> ini = parseIniLines(iniFile.readAsLinesSync());
96 97
    final String? path = ini['path'];
    if (path == null) {
98 99
      return androidEmulatorWithoutProperties;
    }
100
    final File configFile = _fileSystem.file(_fileSystem.path.join(path, 'config.ini'));
101 102 103 104 105 106 107 108 109 110 111 112
    if (!configFile.existsSync()) {
      return androidEmulatorWithoutProperties;
    }
    final Map<String, String> properties = parseIniLines(configFile.readAsLinesSync());
    return AndroidEmulator(
      id,
      properties: properties,
      processManager: _processManager,
      logger: _logger,
      androidSdk: _androidSdk,
    );
  }
113 114 115
}

class AndroidEmulator extends Emulator {
116
  AndroidEmulator(String id, {
117 118 119 120
    Map<String, String>? properties,
    required Logger logger,
    AndroidSdk? androidSdk,
    required ProcessManager processManager,
121 122 123 124 125
  }) : _properties = properties,
       _logger = logger,
       _androidSdk = androidSdk,
       _processUtils = ProcessUtils(logger: logger, processManager: processManager),
       super(id, properties != null && properties.isNotEmpty);
126

127
  final Map<String, String>? _properties;
128 129
  final Logger _logger;
  final ProcessUtils _processUtils;
130
  final AndroidSdk? _androidSdk;
131

132 133
  // Android Studio uses the ID with underscores replaced with spaces
  // for the name if displayname is not set so we do the same.
134
  @override
135
  String get name => _prop('avd.ini.displayname') ?? id.replaceAll('_', ' ').trim();
136 137

  @override
138
  String? get manufacturer => _prop('hw.device.manufacturer');
139

140 141 142 143
  @override
  Category get category => Category.mobile;

  @override
144
  PlatformType get platformType => PlatformType.android;
145

146
  String? _prop(String name) => _properties != null ? _properties![name] : null;
147

148
  @override
149 150 151 152 153
  Future<void> launch({@visibleForTesting Duration? startupDuration, bool coldBoot = false}) async {
    final String? emulatorPath = _androidSdk?.emulatorPath;
    if (emulatorPath == null) {
      throw Exception('Emulator is missing from the Android SDK');
    }
154
    final List<String> command = <String>[
155
      emulatorPath,
156 157 158
      '-avd',
      id,
      if (coldBoot)
159
        '-no-snapshot-load',
160 161
    ];
    final Process process = await _processUtils.start(command);
Dan Field's avatar
Dan Field committed
162 163 164 165 166 167 168 169 170 171 172 173

    // Record output from the emulator process.
    final List<String> stdoutList = <String>[];
    final List<String> stderrList = <String>[];
    final StreamSubscription<String> stdoutSubscription = process.stdout
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .listen(stdoutList.add);
    final StreamSubscription<String> stderrSubscription = process.stderr
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .listen(stderrList.add);
174
    final Future<void> stdioFuture = Future.wait<void>(<Future<void>>[
Dan Field's avatar
Dan Field committed
175 176
      stdoutSubscription.asFuture<void>(),
      stderrSubscription.asFuture<void>(),
177
    ]);
Dan Field's avatar
Dan Field committed
178 179 180 181 182 183 184 185

    // The emulator continues running on success, so we don't wait for the
    // process to complete before continuing. However, if the process fails
    // after the startup phase (3 seconds), then we only echo its output if
    // its error code is non-zero and its stderr is non-empty.
    bool earlyFailure = true;
    unawaited(process.exitCode.then((int status) async {
      if (status == 0) {
186
        _logger.printTrace('The Android emulator exited successfully');
Dan Field's avatar
Dan Field committed
187 188 189 190 191 192 193
        return;
      }
      // Make sure the process' stdout and stderr are drained.
      await stdioFuture;
      unawaited(stdoutSubscription.cancel());
      unawaited(stderrSubscription.cancel());
      if (stdoutList.isNotEmpty) {
194 195
        _logger.printTrace('Android emulator stdout:');
        stdoutList.forEach(_logger.printTrace);
Dan Field's avatar
Dan Field committed
196 197
      }
      if (!earlyFailure && stderrList.isEmpty) {
198
        _logger.printStatus('The Android emulator exited with code $status');
Dan Field's avatar
Dan Field committed
199 200 201
        return;
      }
      final String when = earlyFailure ? 'during startup' : 'after startup';
202 203 204 205
      _logger.printError('The Android emulator exited with code $status $when');
      _logger.printError('Android emulator stderr:');
      stderrList.forEach(_logger.printError);
      _logger.printError('Address these issues and try again.');
Dan Field's avatar
Dan Field committed
206 207 208
    }));

    // Wait a few seconds for the emulator to start.
209
    await Future<void>.delayed(startupDuration ?? const Duration(seconds: 3));
Dan Field's avatar
Dan Field committed
210 211
    earlyFailure = false;
    return;
212
  }
213 214
}

215

216
@visibleForTesting
217
Map<String, String> parseIniLines(List<String> contents) {
218 219 220
  final Map<String, String> results = <String, String>{};

  final Iterable<List<String>> properties = contents
221
      .map<String>((String l) => l.trim())
Danny Tuppeny's avatar
Danny Tuppeny committed
222 223 224 225 226
      // Strip blank lines/comments
      .where((String l) => l != '' && !l.startsWith('#'))
      // Discard anything that isn't simple name=value
      .where((String l) => l.contains('='))
      // Split into name/value
227
      .map<List<String>>((String l) => l.split('='));
228

229
  for (final List<String> property in properties) {
230
    results[property[0].trim()] = property[1].trim();
231
  }
232 233

  return results;
234
}