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

5
import 'dart:async';
Devon Carew's avatar
Devon Carew committed
6
import 'dart:math' as math;
7

8
import 'package:meta/meta.dart';
9
import 'package:process/process.dart';
10
import 'package:vm_service/vm_service.dart' as vm_service;
11

12
import 'android/android_device_discovery.dart';
13
import 'android/android_sdk.dart';
14
import 'android/android_workflow.dart';
15
import 'application_package.dart';
16
import 'artifacts.dart';
17
import 'base/common.dart';
18
import 'base/config.dart';
19
import 'base/context.dart';
20
import 'base/dds.dart';
21
import 'base/file_system.dart';
22
import 'base/io.dart';
23 24
import 'base/logger.dart';
import 'base/platform.dart';
25
import 'base/user_messages.dart';
26
import 'base/utils.dart';
27
import 'build_info.dart';
28
import 'features.dart';
29
import 'fuchsia/fuchsia_device.dart';
30 31
import 'fuchsia/fuchsia_sdk.dart';
import 'fuchsia/fuchsia_workflow.dart';
32
import 'globals.dart' as globals;
33
import 'ios/devices.dart';
34
import 'ios/ios_workflow.dart';
35
import 'ios/simulators.dart';
36 37
import 'linux/linux_device.dart';
import 'macos/macos_device.dart';
38
import 'macos/macos_workflow.dart';
39
import 'macos/xcode.dart';
40
import 'project.dart';
41
import 'tester/flutter_tester.dart';
42
import 'version.dart';
43
import 'web/web_device.dart';
44
import 'windows/windows_device.dart';
45

46
DeviceManager get deviceManager => context.get<DeviceManager>();
47

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/// A description of the kind of workflow the device supports.
class Category {
  const Category._(this.value);

  static const Category web = Category._('web');
  static const Category desktop = Category._('desktop');
  static const Category mobile = Category._('mobile');

  final String value;

  @override
  String toString() => value;
}

/// The platform sub-folder that a device type supports.
class PlatformType {
  const PlatformType._(this.value);

  static const PlatformType web = PlatformType._('web');
  static const PlatformType android = PlatformType._('android');
  static const PlatformType ios = PlatformType._('ios');
  static const PlatformType linux = PlatformType._('linux');
  static const PlatformType macos = PlatformType._('macos');
  static const PlatformType windows = PlatformType._('windows');
  static const PlatformType fuchsia = PlatformType._('fuchsia');

  final String value;

  @override
  String toString() => value;
}

80
/// A class to get all available devices.
81
abstract class DeviceManager {
82

83
  /// Constructing DeviceManagers is cheap; they only do expensive work if some
84
  /// of their methods are called.
85
  List<DeviceDiscovery> get deviceDiscoverers;
86

87 88
  String _specifiedDeviceId;

89
  /// A user-specified device ID.
90
  String get specifiedDeviceId {
91
    if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') {
92
      return null;
93
    }
94 95
    return _specifiedDeviceId;
  }
96

97 98 99 100 101
  set specifiedDeviceId(String id) {
    _specifiedDeviceId = id;
  }

  /// True when the user has specified a single specific device.
102
  bool get hasSpecifiedDeviceId => specifiedDeviceId != null;
103

104 105 106 107
  /// True when the user has specified all devices by setting
  /// specifiedDeviceId = 'all'.
  bool get hasSpecifiedAllDevices => _specifiedDeviceId == 'all';

108
  Future<List<Device>> getDevicesById(String deviceId) async {
109
    final String lowerDeviceId = deviceId.toLowerCase();
110
    bool exactlyMatchesDeviceId(Device device) =>
111 112
        device.id.toLowerCase() == lowerDeviceId ||
        device.name.toLowerCase() == lowerDeviceId;
113
    bool startsWithDeviceId(Device device) =>
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        device.id.toLowerCase().startsWith(lowerDeviceId) ||
        device.name.toLowerCase().startsWith(lowerDeviceId);

    // Some discoverers have hard-coded device IDs and return quickly, and others
    // shell out to other processes and can take longer.
    // Process discoverers as they can return results, so if an exact match is
    // found quickly, we don't wait for all the discoverers to complete.
    final List<Device> prefixMatches = <Device>[];
    final Completer<Device> exactMatchCompleter = Completer<Device>();
    final List<Future<List<Device>>> futureDevices = <Future<List<Device>>>[
      for (final DeviceDiscovery discoverer in _platformDiscoverers)
        discoverer
        .devices
        .then((List<Device> devices) {
          for (final Device device in devices) {
            if (exactlyMatchesDeviceId(device)) {
              exactMatchCompleter.complete(device);
              return null;
            }
            if (startsWithDeviceId(device)) {
              prefixMatches.add(device);
            }
          }
          return null;
        }, onError: (dynamic error, StackTrace stackTrace) {
          // Return matches from other discoverers even if one fails.
          globals.printTrace('Ignored error discovering $deviceId: $error');
        })
    ];

    // Wait for an exact match, or for all discoverers to return results.
    await Future.any<dynamic>(<Future<dynamic>>[
      exactMatchCompleter.future,
      Future.wait<List<Device>>(futureDevices),
    ]);

    if (exactMatchCompleter.isCompleted) {
      return <Device>[await exactMatchCompleter.future];
152
    }
153
    return prefixMatches;
Devon Carew's avatar
Devon Carew committed
154 155
  }

156
  /// Returns the list of connected devices, filtered by any user-specified device id.
157
  Future<List<Device>> getDevices() {
158 159 160
    return hasSpecifiedDeviceId
        ? getDevicesById(specifiedDeviceId)
        : getAllConnectedDevices();
161 162
  }

163
  Iterable<DeviceDiscovery> get _platformDiscoverers {
164
    return deviceDiscoverers.where((DeviceDiscovery discoverer) => discoverer.supportsPlatform);
165 166
  }

167
  /// Returns the list of all connected devices.
168 169 170 171 172 173 174
  Future<List<Device>> getAllConnectedDevices() async {
    final List<List<Device>> devices = await Future.wait<List<Device>>(<Future<List<Device>>>[
      for (final DeviceDiscovery discoverer in _platformDiscoverers)
        discoverer.devices,
    ]);

    return devices.expand<Device>((List<Device> deviceList) => deviceList).toList();
175
  }
176

177 178 179 180 181 182 183 184 185 186
  /// Returns the list of all connected devices. Discards existing cache of devices.
  Future<List<Device>> refreshAllConnectedDevices({ Duration timeout }) async {
    final List<List<Device>> devices = await Future.wait<List<Device>>(<Future<List<Device>>>[
      for (final DeviceDiscovery discoverer in _platformDiscoverers)
        discoverer.discoverDevices(timeout: timeout),
    ]);

    return devices.expand<Device>((List<Device> deviceList) => deviceList).toList();
  }

187 188 189 190 191 192 193
  /// Whether we're capable of listing any devices given the current environment configuration.
  bool get canListAnything {
    return _platformDiscoverers.any((DeviceDiscovery discoverer) => discoverer.canListAnything);
  }

  /// Get diagnostics about issues with any connected devices.
  Future<List<String>> getDeviceDiagnostics() async {
194
    return <String>[
195
      for (final DeviceDiscovery discoverer in _platformDiscoverers)
196 197
        ...await discoverer.getDiagnostics(),
    ];
198
  }
199 200 201

  /// Find and return a list of devices based on the current project and environment.
  ///
202
  /// Returns a list of devices specified by the user.
203 204 205 206 207 208 209 210 211 212
  ///
  /// * If the user specified '-d all', then return all connected devices which
  /// support the current project, except for fuchsia and web.
  ///
  /// * If the user specified a device id, then do nothing as the list is already
  /// filtered by [getDevices].
  ///
  /// * If the user did not specify a device id and there is more than one
  /// device connected, then filter out unsupported devices and prioritize
  /// ephemeral devices.
213 214 215 216 217 218
  Future<List<Device>> findTargetDevices(FlutterProject flutterProject, { Duration timeout }) async {
    if (timeout != null) {
      // Reset the cache with the specified timeout.
      await refreshAllConnectedDevices(timeout: timeout);
    }

219
    List<Device> devices = await getDevices();
220

221 222 223 224 225 226
    // Always remove web and fuchsia devices from `--all`. This setting
    // currently requires devices to share a frontend_server and resident
    // runnner instance. Both web and fuchsia require differently configured
    // compilers, and web requires an entirely different resident runner.
    if (hasSpecifiedAllDevices) {
      devices = <Device>[
227
        for (final Device device in devices)
228 229
          if (await device.targetPlatform != TargetPlatform.fuchsia_arm64 &&
              await device.targetPlatform != TargetPlatform.fuchsia_x64 &&
230
              await device.targetPlatform != TargetPlatform.web_javascript)
231
            device,
232 233 234 235 236 237 238 239
      ];
    }

    // If there is no specified device, the remove all devices which are not
    // supported by the current application. For example, if there was no
    // 'android' folder then don't attempt to launch with an Android device.
    if (devices.length > 1 && !hasSpecifiedDeviceId) {
      devices = <Device>[
240
        for (final Device device in devices)
241
          if (isDeviceSupportedForProject(device, flutterProject))
242
            device,
243
      ];
244 245 246 247 248 249
    } else if (devices.length == 1 &&
             !hasSpecifiedDeviceId &&
             !isDeviceSupportedForProject(devices.single, flutterProject)) {
      // If there is only a single device but it is not supported, then return
      // early.
      return <Device>[];
250
    }
251

252 253
    // If there are still multiple devices and the user did not specify to run
    // all, then attempt to prioritize ephemeral devices. For example, if the
254
    // user only typed 'flutter run' and both an Android device and desktop
255 256
    // device are availible, choose the Android device.
    if (devices.length > 1 && !hasSpecifiedAllDevices) {
257 258 259
      // Note: ephemeral is nullable for device types where this is not well
      // defined.
      if (devices.any((Device device) => device.ephemeral == true)) {
260 261
        // if there is only one ephemeral device, get it
        final List<Device> ephemeralDevices = devices
262 263
            .where((Device device) => device.ephemeral == true)
            .toList();
264 265 266 267 268 269 270 271 272 273 274 275 276

            if (ephemeralDevices.length == 1){
              devices = ephemeralDevices;
            }
      }
      // If it was not able to prioritize a device. For example, if the user
      // has two active Android devices running, then we request the user to
      // choose one. If the user has two nonEphemeral devices running, we also
      // request input to choose one.
      if (devices.length > 1 && globals.stdio.stdinHasTerminal) {
        globals.printStatus(globals.userMessages.flutterMultipleDevicesFound);
        await Device.printDevices(devices);
        final Device chosenDevice = await _chooseOneOfAvailableDevices(devices);
277
        globals.deviceManager.specifiedDeviceId = chosenDevice.id;
278
        devices = <Device>[chosenDevice];
279 280 281 282 283
      }
    }
    return devices;
  }

284 285 286
  Future<Device> _chooseOneOfAvailableDevices(List<Device> devices) async {
    _displayDeviceOptions(devices);
    final String userInput =  await _readUserInput(devices.length);
287 288 289
    if (userInput.toLowerCase() == 'q') {
      throwToolExit('');
    }
290 291 292 293 294 295 296 297 298 299 300 301 302 303
    return devices[int.parse(userInput)];
  }

  void _displayDeviceOptions(List<Device> devices) {
    int count = 0;
    for (final Device device in devices) {
      globals.printStatus(userMessages.flutterChooseDevice(count, device.name, device.id));
      count++;
    }
  }

  Future<String> _readUserInput(int deviceCount) async {
    globals.terminal.usesTerminalUi = true;
    final String result = await globals.terminal.promptForCharInput(
304 305
        <String>[ for (int i = 0; i < deviceCount; i++) '$i', 'q', 'Q'],
        displayAcceptedCharacters: false,
306 307 308 309 310
        logger: globals.logger,
        prompt: userMessages.flutterChooseOne);
    return result;
  }

311
  /// Returns whether the device is supported for the project.
312
  ///
313
  /// This exists to allow the check to be overridden for google3 clients.
314 315 316
  bool isDeviceSupportedForProject(Device device, FlutterProject flutterProject) {
    return device.isSupportedForProject(flutterProject);
  }
317 318
}

319
class FlutterDeviceManager extends DeviceManager {
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  FlutterDeviceManager({
    @required Logger logger,
    @required Platform platform,
    @required ProcessManager processManager,
    @required FileSystem fileSystem,
    @required AndroidSdk androidSdk,
    @required FeatureFlags featureFlags,
    @required IOSSimulatorUtils iosSimulatorUtils,
    @required XCDevice xcDevice,
    @required AndroidWorkflow androidWorkflow,
    @required IOSWorkflow iosWorkflow,
    @required FuchsiaWorkflow fuchsiaWorkflow,
    @required FlutterVersion flutterVersion,
    @required Config config,
    @required Artifacts artifacts,
335
    @required MacOSWorkflow macOSWorkflow,
336
  }) : deviceDiscoverers =  <DeviceDiscovery>[
337
    AndroidDevices(
338 339
      logger: logger,
      androidSdk: androidSdk,
340
      androidWorkflow: androidWorkflow,
341
      processManager: processManager,
342 343
    ),
    IOSDevices(
344 345 346 347 348 349 350
      platform: platform,
      xcdevice: xcDevice,
      iosWorkflow: iosWorkflow,
      logger: logger,
    ),
    IOSSimulators(
      iosSimulatorUtils: iosSimulatorUtils,
351 352 353
    ),
    FuchsiaDevices(
      fuchsiaSdk: fuchsiaSdk,
354
      logger: logger,
355
      fuchsiaWorkflow: fuchsiaWorkflow,
356 357 358 359 360 361 362 363 364
      platform: platform,
    ),
    FlutterTesterDevices(
      fileSystem: fileSystem,
      flutterVersion: flutterVersion,
      processManager: processManager,
      config: config,
      logger: logger,
      artifacts: artifacts,
365
    ),
366 367 368 369 370
    MacOSDevices(
      processManager: processManager,
      macOSWorkflow: macOSWorkflow,
      logger: logger,
      platform: platform,
371
      fileSystem: fileSystem,
372
    ),
373
    LinuxDevices(
374
      platform: platform,
375
      featureFlags: featureFlags,
376 377
      processManager: processManager,
      logger: logger,
378
      fileSystem: fileSystem,
379 380 381 382
    ),
    WindowsDevices(),
    WebDevices(
      featureFlags: featureFlags,
383 384 385 386
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      logger: logger,
387 388
    ),
  ];
389 390 391

  @override
  final List<DeviceDiscovery> deviceDiscoverers;
392 393
}

394 395 396
/// An abstract class to discover and enumerate a specific type of devices.
abstract class DeviceDiscovery {
  bool get supportsPlatform;
397 398 399 400 401

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

402
  /// Return all connected devices, cached on subsequent calls.
403
  Future<List<Device>> get devices;
404

405 406 407
  /// Return all connected devices. Discards existing cache of devices.
  Future<List<Device>> discoverDevices({ Duration timeout });

408 409
  /// Gets a list of diagnostic messages pertaining to issues with any connected
  /// devices (will be an empty list if there are no issues).
410
  Future<List<String>> getDiagnostics() => Future<List<String>>.value(<String>[]);
411 412
}

413 414 415 416 417
/// A [DeviceDiscovery] implementation that uses polling to discover device adds
/// and removals.
abstract class PollingDeviceDiscovery extends DeviceDiscovery {
  PollingDeviceDiscovery(this.name);

418 419
  static const Duration _pollingInterval = Duration(seconds: 4);
  static const Duration _pollingTimeout = Duration(seconds: 30);
420 421

  final String name;
422 423 424 425 426

  @protected
  @visibleForTesting
  ItemListNotifier<Device> deviceNotifier;

427
  Timer _timer;
428

429
  Future<List<Device>> pollingGetDevices({ Duration timeout });
430

431
  Future<void> startPolling() async {
432
    if (_timer == null) {
433
      deviceNotifier ??= ItemListNotifier<Device>();
434 435
      // Make initial population the default, fast polling timeout.
      _timer = _initTimer(null);
436 437 438
    }
  }

439
  Timer _initTimer(Duration pollingTimeout) {
440 441
    return Timer(_pollingInterval, () async {
      try {
442
        final List<Device> devices = await pollingGetDevices(timeout: pollingTimeout);
443
        deviceNotifier.updateWithNewList(devices);
444
      } on TimeoutException {
445
        globals.printTrace('Device poll timed out. Will retry.');
446
      }
447 448
      // Subsequent timeouts after initial population should wait longer.
      _timer = _initTimer(_pollingTimeout);
449 450 451
    });
  }

452
  Future<void> stopPolling() async {
453 454
    _timer?.cancel();
    _timer = null;
455 456
  }

457
  @override
458
  Future<List<Device>> get devices async {
459 460 461 462 463
    return _populateDevices();
  }

  @override
  Future<List<Device>> discoverDevices({ Duration timeout }) async {
464
    deviceNotifier = null;
465 466 467 468
    return _populateDevices(timeout: timeout);
  }

  Future<List<Device>> _populateDevices({ Duration timeout }) async {
469 470
    deviceNotifier ??= ItemListNotifier<Device>.from(await pollingGetDevices(timeout: timeout));
    return deviceNotifier.items;
471 472 473
  }

  Stream<Device> get onAdded {
474 475
    deviceNotifier ??= ItemListNotifier<Device>();
    return deviceNotifier.onAdded;
476 477 478
  }

  Stream<Device> get onRemoved {
479 480
    deviceNotifier ??= ItemListNotifier<Device>();
    return deviceNotifier.onRemoved;
481 482
  }

483
  Future<void> dispose() async => await stopPolling();
484

485
  @override
486 487 488
  String toString() => '$name device discovery';
}

489 490 491 492
/// A device is a physical hardware that can run a flutter application.
///
/// This may correspond to a connected iOS or Android device, or represent
/// the host operating system in the case of Flutter Desktop.
493
abstract class Device {
494 495 496 497 498
  Device(this.id, {
    @required this.category,
    @required this.platformType,
    @required this.ephemeral,
  });
499

500
  final String id;
501

502 503 504 505 506 507 508 509 510
  /// The [Category] for this device type.
  final Category category;

  /// The [PlatformType] for this device.
  final PlatformType platformType;

  /// Whether this is an ephemeral device.
  final bool ephemeral;

511 512
  String get name;

513 514
  bool get supportsStartPaused => true;

515
  /// Whether it is an emulated device running on localhost.
516 517 518
  ///
  /// This may return `true` for certain physical Android devices, and is
  /// generally only a best effort guess.
519
  Future<bool> get isLocalEmulator;
520

521 522 523 524 525 526 527 528
  /// The unique identifier for the emulator that corresponds to this device, or
  /// null if it is not an emulator.
  ///
  /// The ID returned matches that in the output of `flutter emulators`. Fetching
  /// this name may require connecting to the device and if an error occurs null
  /// will be returned.
  Future<String> get emulatorId;

529 530 531 532 533 534
  /// Whether this device can run the provided [buildMode].
  ///
  /// For example, some emulator architectures cannot run profile or
  /// release builds.
  FutureOr<bool> supportsRuntimeMode(BuildMode buildMode) => true;

535
  /// Whether the device is a simulator on a platform which supports hardware rendering.
536
  // This is soft-deprecated since the logic is not correct expect for iOS simulators.
537
  Future<bool> get supportsHardwareRendering async {
538
    return true;
539 540
  }

541 542 543
  /// Whether the device is supported for the current project directory.
  bool isSupportedForProject(FlutterProject flutterProject);

544 545 546 547 548 549 550
  /// Check if a version of the given app is already installed.
  ///
  /// Specify [userIdentifier] to check if installed for a particular user (Android only).
  Future<bool> isAppInstalled(
    covariant ApplicationPackage app, {
    String userIdentifier,
  });
551

552
  /// Check if the latest build of the [app] is already installed.
553
  Future<bool> isLatestBuildInstalled(covariant ApplicationPackage app);
554

555 556 557 558 559 560 561
  /// Install an app package on the current device.
  ///
  /// Specify [userIdentifier] to install for a particular user (Android only).
  Future<bool> installApp(
    covariant ApplicationPackage app, {
    String userIdentifier,
  });
562

563 564 565 566 567 568 569 570
  /// Uninstall an app package from the current device.
  ///
  /// Specify [userIdentifier] to uninstall for a particular user,
  /// defaults to all users (Android only).
  Future<bool> uninstallApp(
    covariant ApplicationPackage app, {
    String userIdentifier,
  });
571

572
  /// Check if the device is supported by Flutter.
573 574 575 576
  bool isSupported();

  // String meant to be displayed to the user indicating if the device is
  // supported by Flutter, and, if not, why.
577
  String supportMessage() => isSupported() ? 'Supported' : 'Unsupported';
578

579 580
  /// The device's platform.
  Future<TargetPlatform> get targetPlatform;
581

582
  Future<String> get sdkNameAndVersion;
583

584
  /// Get a log reader for this device.
585 586
  ///
  /// If `app` is specified, this will return a log reader specific to that
587
  /// application. Otherwise, a global log reader will be returned.
588 589 590 591 592 593 594 595
  ///
  /// If `includePastLogs` is true and the device type supports it, the log
  /// reader will also include log messages from before the invocation time.
  /// Defaults to false.
  FutureOr<DeviceLogReader> getLogReader({
    covariant ApplicationPackage app,
    bool includePastLogs = false,
  });
596

597 598 599
  /// Get the port forwarder for this device.
  DevicePortForwarder get portForwarder;

600 601 602 603 604 605
  /// Get the DDS instance for this device.
  DartDevelopmentService get dds => _dds ??= DartDevelopmentService(
    logger: globals.logger,
  );
  DartDevelopmentService _dds;

606 607
  /// Clear the device's logs.
  void clearLogs();
608

609 610 611
  /// Optional device-specific artifact overrides.
  OverrideArtifacts get artifactOverrides => null;

612 613 614
  /// Start an app package on the current device.
  ///
  /// [platformArgs] allows callers to pass platform-specific arguments to the
615
  /// start call. The build mode is not used by all platforms.
Devon Carew's avatar
Devon Carew committed
616
  Future<LaunchResult> startApp(
617
    covariant ApplicationPackage package, {
618 619
    String mainPath,
    String route,
Devon Carew's avatar
Devon Carew committed
620
    DebuggingOptions debuggingOptions,
621
    Map<String, dynamic> platformArgs,
622 623
    bool prebuiltApplication = false,
    bool ipv6 = false,
624
    String userIdentifier,
625
  });
626

627 628 629 630 631
  /// Whether this device implements support for hot reload.
  bool get supportsHotReload => true;

  /// Whether this device implements support for hot restart.
  bool get supportsHotRestart => true;
632

633 634
  /// Whether flutter applications running on this device can be terminated
  /// from the vmservice.
635
  bool get supportsFlutterExit => true;
636

637 638
  /// Whether the device supports taking screenshots of a running flutter
  /// application.
Devon Carew's avatar
Devon Carew committed
639 640
  bool get supportsScreenshot => false;

641 642 643
  /// Whether the device supports the '--fast-start' development mode.
  bool get supportsFastStart => false;

644
  /// Stop an app package on the current device.
645 646 647 648 649 650
  ///
  /// Specify [userIdentifier] to stop app installed to a profile (Android only).
  Future<bool> stopApp(
    covariant ApplicationPackage app, {
    String userIdentifier,
  });
651

652 653 654 655 656 657 658 659
  /// Query the current application memory usage..
  ///
  /// If the device does not support this callback, an empty map
  /// is returned.
  Future<MemoryInfo> queryMemoryInfo() {
    return Future<MemoryInfo>.value(const MemoryInfo.empty());
  }

660
  Future<void> takeScreenshot(File outputFile) => Future<void>.error('unimplemented');
Devon Carew's avatar
Devon Carew committed
661

662
  @nonVirtual
663
  @override
664
  // ignore: avoid_equals_and_hash_code_on_mutable_classes
665 666
  int get hashCode => id.hashCode;

667
  @nonVirtual
668
  @override
669
  // ignore: avoid_equals_and_hash_code_on_mutable_classes
670
  bool operator ==(Object other) {
671
    if (identical(this, other)) {
672
      return true;
673
    }
674 675
    return other is Device
        && other.id == id;
676 677
  }

678
  @override
679
  String toString() => name;
Devon Carew's avatar
Devon Carew committed
680

681
  static Stream<String> descriptions(List<Device> devices) async* {
682
    if (devices.isEmpty) {
683
      return;
684
    }
Devon Carew's avatar
Devon Carew committed
685

686
    // Extract device information
687
    final List<List<String>> table = <List<String>>[];
688
    for (final Device device in devices) {
Devon Carew's avatar
Devon Carew committed
689
      String supportIndicator = device.isSupported() ? '' : ' (unsupported)';
690 691 692
      final TargetPlatform targetPlatform = await device.targetPlatform;
      if (await device.isLocalEmulator) {
        final String type = targetPlatform == TargetPlatform.ios ? 'simulator' : 'emulator';
693 694
        supportIndicator += ' ($type)';
      }
695
      table.add(<String>[
696
        '${device.name} (${device.category})',
697
        device.id,
698
        getNameForTargetPlatform(targetPlatform),
699
        '${await device.sdkNameAndVersion}$supportIndicator',
700 701 702 703
      ]);
    }

    // Calculate column widths
704
    final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i);
705
    List<int> widths = indices.map<int>((int i) => 0).toList();
706
    for (final List<String> row in table) {
707
      widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList();
708 709 710
    }

    // Join columns into lines of text
711
    for (final List<String> row in table) {
712
      yield indices.map<String>((int i) => row[i].padRight(widths[i])).join(' • ') + ' • ${row.last}';
713
    }
714 715
  }

716
  static Future<void> printDevices(List<Device> devices) async {
717
    await descriptions(devices).forEach(globals.printStatus);
Devon Carew's avatar
Devon Carew committed
718
  }
719

720 721 722 723 724 725 726
  static List<String> devicesPlatformTypes(List<Device> devices) {
    return devices
        .map(
          (Device d) => d.platformType.toString(),
        ).toSet().toList()..sort();
  }

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
  /// Convert the Device object to a JSON representation suitable for serialization.
  Future<Map<String, Object>> toJson() async {
    final bool isLocalEmu = await isLocalEmulator;
    return <String, Object>{
      'name': name,
      'id': id,
      'isSupported': isSupported(),
      'targetPlatform': getNameForTargetPlatform(await targetPlatform),
      'emulator': isLocalEmu,
      'sdk': await sdkNameAndVersion,
      'capabilities': <String, Object>{
        'hotReload': supportsHotReload,
        'hotRestart': supportsHotRestart,
        'screenshot': supportsScreenshot,
        'fastStart': supportsFastStart,
        'flutterExit': supportsFlutterExit,
        'hardwareRendering': isLocalEmu && await supportsHardwareRendering,
        'startPaused': supportsStartPaused,
      }
    };
  }

749
  /// Clean up resources allocated by device.
750 751
  ///
  /// For example log readers or port forwarders.
752
  Future<void> dispose();
753 754
}

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
/// Information about an application's memory usage.
abstract class MemoryInfo {
  /// Const constructor to allow subclasses to be const.
  const MemoryInfo();

  /// Create a [MemoryInfo] object with no information.
  const factory MemoryInfo.empty() = _NoMemoryInfo;

  /// Convert the object to a JSON representation suitable for serialization.
  Map<String, Object> toJson();
}

class _NoMemoryInfo implements MemoryInfo {
  const _NoMemoryInfo();

  @override
  Map<String, Object> toJson() => <String, Object>{};
}

Devon Carew's avatar
Devon Carew committed
774
class DebuggingOptions {
775 776
  DebuggingOptions.enabled(
    this.buildInfo, {
777
    this.startPaused = false,
778
    this.disableServiceAuthCodes = false,
779
    this.disableDds = false,
780
    this.dartFlags = '',
781 782 783
    this.enableSoftwareRendering = false,
    this.skiaDeterministicRendering = false,
    this.traceSkia = false,
784
    this.traceAllowlist,
785
    this.traceSystrace = false,
786
    this.endlessTraceBuffer = false,
787
    this.dumpSkpOnShaderCompilation = false,
788
    this.cacheSkSL = false,
789
    this.purgePersistentCache = false,
790
    this.useTestFonts = false,
791
    this.verboseSystemLogs = false,
792 793
    this.hostVmServicePort,
    this.deviceVmServicePort,
794
    this.ddsPort,
795
    this.initializePlatform = true,
796 797
    this.hostname,
    this.port,
798
    this.webEnableExposeUrl,
799
    this.webUseSseForDebugProxy = true,
800
    this.webUseSseForDebugBackend = true,
801 802
    this.webRunHeadless = false,
    this.webBrowserDebugPort,
803
    this.webEnableExpressionEvaluation = false,
804
    this.vmserviceOutFile,
805
    this.fastStart = false,
806
    this.nullAssertions = false,
Devon Carew's avatar
Devon Carew committed
807 808
   }) : debuggingEnabled = true;

809 810 811 812 813
  DebuggingOptions.disabled(this.buildInfo, {
      this.initializePlatform = true,
      this.port,
      this.hostname,
      this.webEnableExposeUrl,
814
      this.webUseSseForDebugProxy = true,
815
      this.webUseSseForDebugBackend = true,
816 817
      this.webRunHeadless = false,
      this.webBrowserDebugPort,
818
      this.cacheSkSL = false,
819
      this.traceAllowlist,
820
    }) : debuggingEnabled = false,
821 822
      useTestFonts = false,
      startPaused = false,
823
      dartFlags = '',
824
      disableServiceAuthCodes = false,
825
      disableDds = false,
826 827 828 829
      enableSoftwareRendering = false,
      skiaDeterministicRendering = false,
      traceSkia = false,
      traceSystrace = false,
830
      endlessTraceBuffer = false,
831
      dumpSkpOnShaderCompilation = false,
832
      purgePersistentCache = false,
833
      verboseSystemLogs = false,
834 835
      hostVmServicePort = null,
      deviceVmServicePort = null,
836
      ddsPort = null,
837
      vmserviceOutFile = null,
838
      fastStart = false,
839 840
      webEnableExpressionEvaluation = false,
      nullAssertions = false;
Devon Carew's avatar
Devon Carew committed
841 842 843

  final bool debuggingEnabled;

844
  final BuildInfo buildInfo;
Devon Carew's avatar
Devon Carew committed
845
  final bool startPaused;
846
  final String dartFlags;
847
  final bool disableServiceAuthCodes;
848
  final bool disableDds;
849
  final bool enableSoftwareRendering;
850
  final bool skiaDeterministicRendering;
851
  final bool traceSkia;
852
  final String traceAllowlist;
853
  final bool traceSystrace;
854
  final bool endlessTraceBuffer;
855
  final bool dumpSkpOnShaderCompilation;
856
  final bool cacheSkSL;
857
  final bool purgePersistentCache;
858
  final bool useTestFonts;
859
  final bool verboseSystemLogs;
860 861
  /// Whether to invoke webOnlyInitializePlatform in Flutter for web.
  final bool initializePlatform;
862 863
  final int hostVmServicePort;
  final int deviceVmServicePort;
864
  final int ddsPort;
865 866
  final String port;
  final String hostname;
867
  final bool webEnableExposeUrl;
868
  final bool webUseSseForDebugProxy;
869
  final bool webUseSseForDebugBackend;
870 871 872 873 874 875 876 877 878 879 880

  /// Whether to run the browser in headless mode.
  ///
  /// Some CI environments do not provide a display and fail to launch the
  /// browser with full graphics stack. Some browsers provide a special
  /// "headless" mode that runs the browser with no graphics.
  final bool webRunHeadless;

  /// The port the browser should use for its debugging protocol.
  final int webBrowserDebugPort;

881
  /// Enable expression evaluation for web target.
882 883
  final bool webEnableExpressionEvaluation;

884
  /// A file where the vmservice URL should be written after the application is started.
885
  final String vmserviceOutFile;
886
  final bool fastStart;
Devon Carew's avatar
Devon Carew committed
887

888 889
  final bool nullAssertions;

890
  bool get hasObservatoryPort => hostVmServicePort != null;
Devon Carew's avatar
Devon Carew committed
891 892 893
}

class LaunchResult {
894
  LaunchResult.succeeded({ this.observatoryUri }) : started = true;
895 896 897
  LaunchResult.failed()
    : started = false,
      observatoryUri = null;
Devon Carew's avatar
Devon Carew committed
898

899
  bool get hasObservatory => observatoryUri != null;
Devon Carew's avatar
Devon Carew committed
900 901

  final bool started;
902
  final Uri observatoryUri;
Devon Carew's avatar
Devon Carew committed
903 904 905

  @override
  String toString() {
906
    final StringBuffer buf = StringBuffer('started=$started');
907
    if (observatoryUri != null) {
908
      buf.write(', observatory=$observatoryUri');
909
    }
Devon Carew's avatar
Devon Carew committed
910 911 912 913
    return buf.toString();
  }
}

914
class ForwardedPort {
915 916
  ForwardedPort(this.hostPort, this.devicePort) : context = null;
  ForwardedPort.withContext(this.hostPort, this.devicePort, this.context);
917 918 919

  final int hostPort;
  final int devicePort;
920
  final Process context;
921

922
  @override
923
  String toString() => 'ForwardedPort HOST:$hostPort to DEVICE:$devicePort';
924 925 926

  /// Kill subprocess (if present) used in forwarding.
  void dispose() {
927 928
    if (context != null) {
      context.kill();
929 930
    }
  }
931 932 933 934 935 936 937 938 939
}

/// Forward ports from the host machine to the device.
abstract class DevicePortForwarder {
  /// Returns a Future that completes with the current list of forwarded
  /// ports for this device.
  List<ForwardedPort> get forwardedPorts;

  /// Forward [hostPort] on the host to [devicePort] on the device.
940
  /// If [hostPort] is null or zero, will auto select a host port.
941
  /// Returns a Future that completes with the host port.
942
  Future<int> forward(int devicePort, { int hostPort });
943 944

  /// Stops forwarding [forwardedPort].
945
  Future<void> unforward(ForwardedPort forwardedPort);
946

947
  /// Cleanup allocated resources, like [forwardedPorts].
948
  Future<void> dispose();
949 950
}

Devon Carew's avatar
Devon Carew committed
951
/// Read the log for a particular device.
Devon Carew's avatar
Devon Carew committed
952 953 954
abstract class DeviceLogReader {
  String get name;

Devon Carew's avatar
Devon Carew committed
955 956
  /// A broadcast stream where each element in the string is a line of log output.
  Stream<String> get logLines;
Devon Carew's avatar
Devon Carew committed
957

958 959
  /// Some logs can be obtained from a VM service stream.
  /// Set this after the VM services are connected.
960
  vm_service.VmService connectedVMService;
961

962
  @override
Devon Carew's avatar
Devon Carew committed
963
  String toString() => name;
964

965
  /// Process ID of the app on the device.
966
  int appPid;
967 968

  // Clean up resources allocated by log reader e.g. subprocesses
969
  void dispose();
Devon Carew's avatar
Devon Carew committed
970
}
971 972 973

/// Describes an app running on the device.
class DiscoveredApp {
974
  DiscoveredApp(this.id, this.observatoryPort);
975 976 977
  final String id;
  final int observatoryPort;
}
978 979 980 981 982 983 984 985 986 987 988

// An empty device log reader
class NoOpDeviceLogReader implements DeviceLogReader {
  NoOpDeviceLogReader(this.name);

  @override
  final String name;

  @override
  int appPid;

989
  @override
990
  vm_service.VmService connectedVMService;
991

992 993
  @override
  Stream<String> get logLines => const Stream<String>.empty();
994 995 996

  @override
  void dispose() { }
997 998 999 1000 1001 1002 1003
}

// A portforwarder which does not support forwarding ports.
class NoOpDevicePortForwarder implements DevicePortForwarder {
  const NoOpDevicePortForwarder();

  @override
1004
  Future<int> forward(int devicePort, { int hostPort }) async => devicePort;
1005 1006 1007 1008 1009

  @override
  List<ForwardedPort> get forwardedPorts => <ForwardedPort>[];

  @override
1010
  Future<void> unforward(ForwardedPort forwardedPort) async { }
1011 1012 1013

  @override
  Future<void> dispose() async { }
1014
}
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

/// Append --null_assertions to any existing Dart VM flags if
/// [debuggingOptions.nullAssertions] is true.
String computeDartVmFlags(DebuggingOptions debuggingOptions) {
  return <String>[
    if (debuggingOptions.dartFlags?.isNotEmpty ?? false)
      debuggingOptions.dartFlags,
    if (debuggingOptions.nullAssertions)
      '--null_assertions',
  ].join(',');
}