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

import 'dart:math' as math;

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

10
import 'android/android_emulator.dart';
11
import 'android/android_sdk.dart';
12
import 'android/android_workflow.dart';
13
import 'base/context.dart';
14 15
import 'base/file_system.dart';
import 'base/logger.dart';
16
import 'base/process.dart';
17
import 'device.dart';
18
import 'ios/ios_emulators.dart';
19

20
EmulatorManager? get emulatorManager => context.get<EmulatorManager>();
21 22 23

/// A class to get all available emulators.
class EmulatorManager {
24
  EmulatorManager({
25 26 27 28 29
    AndroidSdk? androidSdk,
    required Logger logger,
    required ProcessManager processManager,
    required AndroidWorkflow androidWorkflow,
    required FileSystem fileSystem,
30 31 32 33 34 35 36 37 38 39
  }) : _androidSdk = androidSdk,
       _processUtils = ProcessUtils(logger: logger, processManager: processManager),
       _androidEmulators = AndroidEmulators(
        androidSdk: androidSdk,
        logger: logger,
        processManager: processManager,
        fileSystem: fileSystem,
        androidWorkflow: androidWorkflow
      ) {
    _emulatorDiscoverers.add(_androidEmulators);
40 41
  }

42
  final AndroidSdk? _androidSdk;
43 44 45 46 47 48 49 50
  final AndroidEmulators _androidEmulators;
  final ProcessUtils _processUtils;

  // Constructing EmulatorManager is cheap; they only do expensive work if some
  // of their methods are called.
  final List<EmulatorDiscovery> _emulatorDiscoverers = <EmulatorDiscovery>[
    IOSEmulators(),
  ];
51

52 53
  Future<List<Emulator>> getEmulatorsMatching(String searchText) async {
    final List<Emulator> emulators = await getAllAvailableEmulators();
54
    searchText = searchText.toLowerCase();
55
    bool exactlyMatchesEmulatorId(Emulator emulator) =>
56 57
        emulator.id.toLowerCase() == searchText ||
        emulator.name.toLowerCase() == searchText;
58
    bool startsWithEmulatorId(Emulator emulator) =>
59 60 61 62 63 64 65 66 67 68
        emulator.id.toLowerCase().startsWith(searchText) == true ||
        emulator.name.toLowerCase().startsWith(searchText) == true;

    Emulator? exactMatch;
    for (final Emulator emulator in emulators) {
      if (exactlyMatchesEmulatorId(emulator)) {
        exactMatch = emulator;
        break;
      }
    }
69
    if (exactMatch != null) {
70
      return <Emulator>[exactMatch];
71 72 73
    }

    // Match on a id or name starting with [emulatorId].
74
    return emulators.where(startsWithEmulatorId).toList();
75 76 77 78 79 80
  }

  Iterable<EmulatorDiscovery> get _platformDiscoverers {
    return _emulatorDiscoverers.where((EmulatorDiscovery discoverer) => discoverer.supportsPlatform);
  }

Danny Tuppeny's avatar
Danny Tuppeny committed
81
  /// Return the list of all available emulators.
82 83
  Future<List<Emulator>> getAllAvailableEmulators() async {
    final List<Emulator> emulators = <Emulator>[];
84
    await Future.forEach<EmulatorDiscovery>(_platformDiscoverers, (EmulatorDiscovery discoverer) async {
85 86 87
      emulators.addAll(await discoverer.emulators);
    });
    return emulators;
88 89
  }

90
  /// Return the list of all available emulators.
91
  Future<CreateEmulatorResult> createEmulator({ String? name }) async {
92
    if (name == null || name.isEmpty) {
93 94 95 96 97 98
      const String autoName = 'flutter_emulator';
      // Don't use getEmulatorsMatching here, as it will only return one
      // if there's an exact match and we need all those with this prefix
      // so we can keep adding suffixes until we miss.
      final List<Emulator> all = await getAllAvailableEmulators();
      final Set<String> takenNames = all
99
          .map<String>((Emulator e) => e.id)
100 101 102 103 104 105 106 107
          .where((String id) => id.startsWith(autoName))
          .toSet();
      int suffix = 1;
      name = autoName;
      while (takenNames.contains(name)) {
        name = '${autoName}_${++suffix}';
      }
    }
108 109 110 111
    final String emulatorName = name!;
    final String? avdManagerPath = _androidSdk?.avdManagerPath;
    if (avdManagerPath == null || !_androidEmulators.canLaunchAnything) {
      return CreateEmulatorResult(emulatorName,
112 113 114
        success: false, error: 'avdmanager is missing from the Android SDK'
      );
    }
115

116
    final String? device = await _getPreferredAvailableDevice(avdManagerPath);
117
    if (device == null) {
118
      return CreateEmulatorResult(emulatorName,
119
          success: false, error: 'No device definitions are available');
120
    }
121

122
    final String? sdkId = await _getPreferredSdkId(avdManagerPath);
123
    if (sdkId == null) {
124
      return CreateEmulatorResult(emulatorName,
125 126 127 128 129
          success: false,
          error:
              'No suitable Android AVD system images are available. You may need to install these'
              ' using sdkmanager, for example:\n'
              '  sdkmanager "system-images;android-27;google_apis_playstore;x86"');
130
    }
131 132 133 134 135

    // Cleans up error output from avdmanager to make it more suitable to show
    // to flutter users. Specifically:
    // - Removes lines that say "null" (!)
    // - Removes lines that tell the user to use '--force' to overwrite emulators
136
    String? cleanError(String? error) {
137
      if (error == null || error.trim() == '') {
138
        return null;
139
      }
140
      return error
141 142 143 144
          .split('\n')
          .where((String l) => l.trim() != 'null')
          .where((String l) =>
              l.trim() != 'Use --force if you want to replace it.')
145 146
          .join('\n')
          .trim();
147
    }
148
    final RunResult runResult = await _processUtils.run(<String>[
149
        avdManagerPath,
150 151
        'create',
        'avd',
152
        '-n', emulatorName,
153 154 155 156
        '-k', sdkId,
        '-d', device,
      ], environment: _androidSdk?.sdkManagerEnv,
    );
157
    return CreateEmulatorResult(
158
      emulatorName,
159 160 161 162 163 164
      success: runResult.exitCode == 0,
      output: runResult.stdout,
      error: cleanError(runResult.stderr),
    );
  }

165
  static const List<String> preferredDevices = <String>[
166 167 168
    'pixel',
    'pixel_xl',
  ];
169

170
  Future<String?> _getPreferredAvailableDevice(String avdManagerPath) async {
171
    final List<String> args = <String>[
172
      avdManagerPath,
173 174
      'list',
      'device',
175
      '-c',
176
    ];
177 178
    final RunResult runResult = await _processUtils.run(args,
        environment: _androidSdk?.sdkManagerEnv);
179
    if (runResult.exitCode != 0) {
180
      return null;
181
    }
182 183 184 185 186 187

    final List<String> availableDevices = runResult.stdout
        .split('\n')
        .where((String l) => preferredDevices.contains(l.trim()))
        .toList();

188 189 190 191 192 193
    for (final String device in preferredDevices) {
      if (availableDevices.contains(device)) {
        return device;
      }
    }
    return null;
194 195
  }

196 197
  static final RegExp _androidApiVersion = RegExp(r';android-(\d+);');

198
  Future<String?> _getPreferredSdkId(String avdManagerPath) async {
199 200 201
    // It seems that to get the available list of images, we need to send a
    // request to create without the image and it'll provide us a list :-(
    final List<String> args = <String>[
202
      avdManagerPath,
203 204 205 206
      'create',
      'avd',
      '-n', 'temp',
    ];
207 208
    final RunResult runResult = await _processUtils.run(args,
        environment: _androidSdk?.sdkManagerEnv);
209 210 211 212

    // Get the list of IDs that match our criteria
    final List<String> availableIDs = runResult.stderr
        .split('\n')
213
        .where((String l) => _androidApiVersion.hasMatch(l))
214 215 216 217 218
        .where((String l) => l.contains('system-images'))
        .where((String l) => l.contains('google_apis_playstore'))
        .toList();

    final List<int> availableApiVersions = availableIDs
219
        .map<String>((String id) => _androidApiVersion.firstMatch(id)!.group(1)!)
220
        .map<int>((String apiVersion) => int.parse(apiVersion))
221 222 223 224 225 226 227 228 229
        .toList();

    // Get the highest Android API version or whats left
    final int apiVersion = availableApiVersions.isNotEmpty
        ? availableApiVersions.reduce(math.max)
        : -1; // Don't match below

    // We're out of preferences, we just have to return the first one with the high
    // API version.
230 231 232 233 234 235
    for (final String id in availableIDs) {
      if (id.contains(';android-$apiVersion;')) {
        return id;
      }
    }
    return null;
236 237
  }

238 239 240 241 242 243 244 245 246 247
  /// Whether we're capable of listing any emulators given the current environment configuration.
  bool get canListAnything {
    return _platformDiscoverers.any((EmulatorDiscovery discoverer) => discoverer.canListAnything);
  }
}

/// An abstract class to discover and enumerate a specific type of emulators.
abstract class EmulatorDiscovery {
  bool get supportsPlatform;

248
  /// Whether this emulator discovery is capable of listing any emulators.
249 250
  bool get canListAnything;

251
  /// Whether this emulator discovery is capable of launching new emulators.
252 253
  bool get canLaunchAnything;

254 255 256
  Future<List<Emulator>> get emulators;
}

257
@immutable
258
abstract class Emulator {
259
  const Emulator(this.id, this.hasConfig);
260 261

  final String id;
262 263
  final bool hasConfig;
  String get name;
264
  String? get manufacturer;
265
  Category get category;
266
  PlatformType get platformType;
267 268 269 270 271

  @override
  int get hashCode => id.hashCode;

  @override
272
  bool operator ==(Object other) {
273
    if (identical(this, other)) {
274
      return true;
275
    }
276 277
    return other is Emulator
        && other.id == id;
278 279
  }

280
  Future<void> launch({bool coldBoot});
281

282 283 284
  @override
  String toString() => name;

285
  static List<String> descriptions(List<Emulator> emulators) {
286
    if (emulators.isEmpty) {
287
      return <String>[];
288
    }
289 290

    // Extract emulators information
291
    final List<List<String>> table = <List<String>>[
292
      for (final Emulator emulator in emulators)
293
        <String>[
294 295
          emulator.id,
          emulator.name,
296
          emulator.manufacturer ?? '',
297
          emulator.platformType.toString(),
298 299
        ],
    ];
300 301

    // Calculate column widths
302
    final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i);
303
    List<int> widths = indices.map<int>((int i) => 0).toList();
304
    for (final List<String> row in table) {
305
      widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList();
306 307 308
    }

    // Join columns into lines of text
309
    final RegExp whiteSpaceAndDots = RegExp(r'[•\s]+$');
310
    return table
311
        .map<String>((List<String> row) {
312
          return indices
313 314 315
            .map<String>((int i) => row[i].padRight(widths[i]))
            .followedBy(<String>[row.last])
            .join(' • ');
316
        })
317
        .map<String>((String line) => line.replaceAll(whiteSpaceAndDots, ''))
318
        .toList();
319 320
  }

321 322
  static void printEmulators(List<Emulator> emulators, Logger logger) {
    descriptions(emulators).forEach(logger.printStatus);
323 324
  }
}
325 326

class CreateEmulatorResult {
327
  CreateEmulatorResult(this.emulatorName, {required this.success, this.output, this.error});
328

329 330
  final bool success;
  final String emulatorName;
331 332
  final String? output;
  final String? error;
333
}