emulator.dart 9.34 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 8
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:math' as math;

import 'android/android_emulator.dart';
9
import 'android/android_sdk.dart';
10
import 'base/context.dart';
11
import 'base/process.dart';
12
import 'device.dart';
13
import 'globals.dart';
14
import 'ios/ios_emulators.dart';
15

16
EmulatorManager get emulatorManager => context.get<EmulatorManager>();
17 18 19 20 21 22 23

/// A class to get all available emulators.
class EmulatorManager {
  /// Constructing EmulatorManager is cheap; they only do expensive work if some
  /// of their methods are called.
  EmulatorManager() {
    // Register the known discoverers.
24 25
    _emulatorDiscoverers.add(AndroidEmulators());
    _emulatorDiscoverers.add(IOSEmulators());
26 27 28 29
  }

  final List<EmulatorDiscovery> _emulatorDiscoverers = <EmulatorDiscovery>[];

30 31
  Future<List<Emulator>> getEmulatorsMatching(String searchText) async {
    final List<Emulator> emulators = await getAllAvailableEmulators();
32
    searchText = searchText.toLowerCase();
33
    bool exactlyMatchesEmulatorId(Emulator emulator) =>
34 35
        emulator.id?.toLowerCase() == searchText ||
        emulator.name?.toLowerCase() == searchText;
36
    bool startsWithEmulatorId(Emulator emulator) =>
37 38
        emulator.id?.toLowerCase()?.startsWith(searchText) == true ||
        emulator.name?.toLowerCase()?.startsWith(searchText) == true;
39

40 41
    final Emulator exactMatch =
        emulators.firstWhere(exactlyMatchesEmulatorId, orElse: () => null);
42
    if (exactMatch != null) {
43
      return <Emulator>[exactMatch];
44 45 46
    }

    // Match on a id or name starting with [emulatorId].
47
    return emulators.where(startsWithEmulatorId).toList();
48 49 50 51 52 53
  }

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

Danny Tuppeny's avatar
Danny Tuppeny committed
54
  /// Return the list of all available emulators.
55 56
  Future<List<Emulator>> getAllAvailableEmulators() async {
    final List<Emulator> emulators = <Emulator>[];
57
    await Future.forEach<EmulatorDiscovery>(_platformDiscoverers, (EmulatorDiscovery discoverer) async {
58 59 60
      emulators.addAll(await discoverer.emulators);
    });
    return emulators;
61 62
  }

63
  /// Return the list of all available emulators.
64
  Future<CreateEmulatorResult> createEmulator({ String name }) async {
65 66 67 68 69 70 71
    if (name == null || name == '') {
      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
72
          .map<String>((Emulator e) => e.id)
73 74 75 76 77 78 79 80 81 82
          .where((String id) => id.startsWith(autoName))
          .toSet();
      int suffix = 1;
      name = autoName;
      while (takenNames.contains(name)) {
        name = '${autoName}_${++suffix}';
      }
    }

    final String device = await _getPreferredAvailableDevice();
83
    if (device == null) {
84
      return CreateEmulatorResult(name,
85
          success: false, error: 'No device definitions are available');
86
    }
87 88

    final String sdkId = await _getPreferredSdkId();
89
    if (sdkId == null) {
90
      return CreateEmulatorResult(name,
91 92 93 94 95
          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"');
96
    }
97 98 99 100 101 102

    // 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
    String cleanError(String error) {
103
      if (error == null || error.trim() == '') {
104
        return null;
105
      }
106
      return error
107 108 109 110
          .split('\n')
          .where((String l) => l.trim() != 'null')
          .where((String l) =>
              l.trim() != 'Use --force if you want to replace it.')
111 112
          .join('\n')
          .trim();
113 114 115 116 117 118 119 120
    }

    final List<String> args = <String>[
      getAvdManagerPath(androidSdk),
      'create',
      'avd',
      '-n', name,
      '-k', sdkId,
121
      '-d', device,
122
    ];
123
    final RunResult runResult = processUtils.runSync(args,
124
        environment: androidSdk?.sdkManagerEnv);
125
    return CreateEmulatorResult(
126 127 128 129 130 131 132
      name,
      success: runResult.exitCode == 0,
      output: runResult.stdout,
      error: cleanError(runResult.stderr),
    );
  }

133
  static const List<String> preferredDevices = <String>[
134 135 136 137 138 139 140 141
    'pixel',
    'pixel_xl',
  ];
  Future<String> _getPreferredAvailableDevice() async {
    final List<String> args = <String>[
      getAvdManagerPath(androidSdk),
      'list',
      'device',
142
      '-c',
143
    ];
144
    final RunResult runResult = processUtils.runSync(args,
145
        environment: androidSdk?.sdkManagerEnv);
146
    if (runResult.exitCode != 0) {
147
      return null;
148
    }
149 150 151 152 153 154 155 156 157 158 159 160

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

    return preferredDevices.firstWhere(
      (String d) => availableDevices.contains(d),
      orElse: () => null,
    );
  }

161
  RegExp androidApiVersion = RegExp(r';android-(\d+);');
162 163 164 165 166 167 168 169 170
  Future<String> _getPreferredSdkId() async {
    // 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>[
      getAvdManagerPath(androidSdk),
      'create',
      'avd',
      '-n', 'temp',
    ];
171
    final RunResult runResult = processUtils.runSync(args,
172
        environment: androidSdk?.sdkManagerEnv);
173 174 175 176 177 178 179 180 181 182

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

    final List<int> availableApiVersions = availableIDs
183 184
        .map<String>((String id) => androidApiVersion.firstMatch(id).group(1))
        .map<int>((String apiVersion) => int.parse(apiVersion))
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        .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.
    return availableIDs.firstWhere(
      (String id) => id.contains(';android-$apiVersion;'),
      orElse: () => null,
    );
  }

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  /// 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;

  /// Whether this emulator discovery is capable of listing any emulators given the
  /// current environment configuration.
  bool get canListAnything;

  Future<List<Emulator>> get emulators;
}

abstract class Emulator {
218
  Emulator(this.id, this.hasConfig);
219 220

  final String id;
221 222 223
  final bool hasConfig;
  String get name;
  String get manufacturer;
224 225
  Category get category;
  PlatformType get platformType;
226 227 228 229 230 231

  @override
  int get hashCode => id.hashCode;

  @override
  bool operator ==(dynamic other) {
232
    if (identical(this, other)) {
233
      return true;
234 235
    }
    if (other is! Emulator) {
236
      return false;
237
    }
238 239 240
    return id == other.id;
  }

241
  Future<void> launch();
242

243 244 245
  @override
  String toString() => name;

246
  static List<String> descriptions(List<Emulator> emulators) {
247
    if (emulators.isEmpty) {
248
      return <String>[];
249
    }
250 251

    // Extract emulators information
252 253 254 255 256 257 258 259 260
    final List<List<String>> table = <List<String>>[
      for (Emulator emulator in emulators)
        <String>[
          emulator.id ?? '',
          emulator.name ?? '',
          emulator.manufacturer ?? '',
          emulator.platformType?.toString() ?? '',
        ],
    ];
261 262

    // Calculate column widths
263
    final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i);
264
    List<int> widths = indices.map<int>((int i) => 0).toList();
265
    for (List<String> row in table) {
266
      widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList();
267 268 269
    }

    // Join columns into lines of text
270
    final RegExp whiteSpaceAndDots = RegExp(r'[•\s]+$');
271
    return table
272
        .map<String>((List<String> row) {
273
          return indices
274
                  .map<String>((int i) => row[i].padRight(widths[i]))
275 276 277
                  .join(' • ') +
              ' • ${row.last}';
        })
278
        .map<String>((String line) => line.replaceAll(whiteSpaceAndDots, ''))
279
        .toList();
280 281
  }

282 283
  static void printEmulators(List<Emulator> emulators) {
    descriptions(emulators).forEach(printStatus);
284 285
  }
}
286 287

class CreateEmulatorResult {
288 289
  CreateEmulatorResult(this.emulatorName, {this.success, this.output, this.error});

290 291 292 293 294
  final bool success;
  final String emulatorName;
  final String output;
  final String error;
}