device.dart 26.2 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:vm_service/vm_service.dart' as vm_service;
10

11 12
import 'android/android_device_discovery.dart';
import 'android/android_workflow.dart';
13
import 'application_package.dart';
14
import 'artifacts.dart';
15
import 'base/context.dart';
16
import 'base/file_system.dart';
17
import 'base/io.dart';
18
import 'base/utils.dart';
19
import 'build_info.dart';
20
import 'features.dart';
21
import 'fuchsia/fuchsia_device.dart';
22 23
import 'fuchsia/fuchsia_sdk.dart';
import 'fuchsia/fuchsia_workflow.dart';
24
import 'globals.dart' as globals;
25 26
import 'ios/devices.dart';
import 'ios/simulators.dart';
27 28
import 'linux/linux_device.dart';
import 'macos/macos_device.dart';
29
import 'project.dart';
30
import 'tester/flutter_tester.dart';
31
import 'web/web_device.dart';
32
import 'windows/windows_device.dart';
33

34
DeviceManager get deviceManager => context.get<DeviceManager>();
35

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/// 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;
}

68 69
/// A class to get all available devices.
class DeviceManager {
70

71
  /// Constructing DeviceManagers is cheap; they only do expensive work if some
72
  /// of their methods are called.
73 74
  List<DeviceDiscovery> get deviceDiscoverers => _deviceDiscoverers;
  final List<DeviceDiscovery> _deviceDiscoverers = List<DeviceDiscovery>.unmodifiable(<DeviceDiscovery>[
75 76 77 78 79 80
    AndroidDevices(
      logger: globals.logger,
      androidSdk: globals.androidSdk,
      androidWorkflow: androidWorkflow,
      processManager: globals.processManager,
    ),
81 82 83 84
    IOSDevices(
      platform: globals.platform,
      xcdevice: globals.xcdevice,
      iosWorkflow: globals.iosWorkflow,
85
      logger: globals.logger,
86
    ),
87
    IOSSimulators(iosSimulatorUtils: globals.iosSimulatorUtils),
88 89 90 91 92 93
    FuchsiaDevices(
      fuchsiaSdk: fuchsiaSdk,
      logger: globals.logger,
      fuchsiaWorkflow: fuchsiaWorkflow,
      platform: globals.platform,
    ),
94
    FlutterTesterDevices(),
95
    MacOSDevices(),
96 97 98 99
    LinuxDevices(
      platform: globals.platform,
      featureFlags: featureFlags,
    ),
100
    WindowsDevices(),
101 102 103 104 105 106
    WebDevices(
      featureFlags: featureFlags,
      fileSystem: globals.fs,
      platform: globals.platform,
      processManager: globals.processManager,
    ),
107
  ]);
108

109 110
  String _specifiedDeviceId;

111
  /// A user-specified device ID.
112
  String get specifiedDeviceId {
113
    if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') {
114
      return null;
115
    }
116 117
    return _specifiedDeviceId;
  }
118

119 120 121 122 123
  set specifiedDeviceId(String id) {
    _specifiedDeviceId = id;
  }

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

126 127 128 129
  /// True when the user has specified all devices by setting
  /// specifiedDeviceId = 'all'.
  bool get hasSpecifiedAllDevices => _specifiedDeviceId == 'all';

130 131
  Future<List<Device>> getDevicesById(String deviceId) async {
    final List<Device> devices = await getAllConnectedDevices();
Devon Carew's avatar
Devon Carew committed
132
    deviceId = deviceId.toLowerCase();
133 134 135 136 137 138 139
    bool exactlyMatchesDeviceId(Device device) =>
        device.id.toLowerCase() == deviceId ||
        device.name.toLowerCase() == deviceId;
    bool startsWithDeviceId(Device device) =>
        device.id.toLowerCase().startsWith(deviceId) ||
        device.name.toLowerCase().startsWith(deviceId);

140 141
    final Device exactMatch = devices.firstWhere(
        exactlyMatchesDeviceId, orElse: () => null);
142
    if (exactMatch != null) {
143
      return <Device>[exactMatch];
144
    }
145

146
    // Match on a id or name starting with [deviceId].
147
    return devices.where(startsWithDeviceId).toList();
Devon Carew's avatar
Devon Carew committed
148 149
  }

150
  /// Returns the list of connected devices, filtered by any user-specified device id.
151
  Future<List<Device>> getDevices() {
152 153 154
    return hasSpecifiedDeviceId
        ? getDevicesById(specifiedDeviceId)
        : getAllConnectedDevices();
155 156
  }

157
  Iterable<DeviceDiscovery> get _platformDiscoverers {
158
    return deviceDiscoverers.where((DeviceDiscovery discoverer) => discoverer.supportsPlatform);
159 160
  }

161
  /// Returns the list of all connected devices.
162 163 164 165 166 167 168
  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();
169
  }
170

171 172 173 174 175 176 177 178 179 180
  /// 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();
  }

181 182 183 184 185 186 187
  /// 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 {
188
    return <String>[
189
      for (final DeviceDiscovery discoverer in _platformDiscoverers)
190 191
        ...await discoverer.getDiagnostics(),
    ];
192
  }
193 194 195

  /// Find and return a list of devices based on the current project and environment.
  ///
196
  /// Returns a list of devices specified by the user.
197 198 199 200 201 202 203 204 205 206
  ///
  /// * 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.
207
  Future<List<Device>> findTargetDevices(FlutterProject flutterProject) async {
208
    List<Device> devices = await getDevices();
209

210 211 212 213 214 215
    // 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>[
216
        for (final Device device in devices)
217 218
          if (await device.targetPlatform != TargetPlatform.fuchsia_arm64 &&
              await device.targetPlatform != TargetPlatform.fuchsia_x64 &&
219
              await device.targetPlatform != TargetPlatform.web_javascript)
220
            device,
221 222 223 224 225 226 227 228
      ];
    }

    // 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>[
229
        for (final Device device in devices)
230
          if (isDeviceSupportedForProject(device, flutterProject))
231
            device,
232
      ];
233 234 235 236 237 238
    } 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>[];
239
    }
240

241 242 243 244 245
    // 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
    // use only typed 'flutter run' and both an Android device and desktop
    // device are availible, choose the Android device.
    if (devices.length > 1 && !hasSpecifiedAllDevices) {
246 247 248 249 250 251 252 253 254 255 256 257
      // Note: ephemeral is nullable for device types where this is not well
      // defined.
      if (devices.any((Device device) => device.ephemeral == true)) {
        devices = devices
            .where((Device device) => device.ephemeral == true)
            .toList();
      }
    }
    return devices;
  }

  /// Returns whether the device is supported for the project.
258
  ///
259
  /// This exists to allow the check to be overridden for google3 clients.
260 261 262
  bool isDeviceSupportedForProject(Device device, FlutterProject flutterProject) {
    return device.isSupportedForProject(flutterProject);
  }
263 264 265 266 267
}

/// An abstract class to discover and enumerate a specific type of devices.
abstract class DeviceDiscovery {
  bool get supportsPlatform;
268 269 270 271 272

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

273
  /// Return all connected devices, cached on subsequent calls.
274
  Future<List<Device>> get devices;
275

276 277 278
  /// Return all connected devices. Discards existing cache of devices.
  Future<List<Device>> discoverDevices({ Duration timeout });

279 280
  /// Gets a list of diagnostic messages pertaining to issues with any connected
  /// devices (will be an empty list if there are no issues).
281
  Future<List<String>> getDiagnostics() => Future<List<String>>.value(<String>[]);
282 283
}

284 285 286 287 288
/// A [DeviceDiscovery] implementation that uses polling to discover device adds
/// and removals.
abstract class PollingDeviceDiscovery extends DeviceDiscovery {
  PollingDeviceDiscovery(this.name);

289 290
  static const Duration _pollingInterval = Duration(seconds: 4);
  static const Duration _pollingTimeout = Duration(seconds: 30);
291 292

  final String name;
293 294 295 296 297

  @protected
  @visibleForTesting
  ItemListNotifier<Device> deviceNotifier;

298
  Timer _timer;
299

300
  Future<List<Device>> pollingGetDevices({ Duration timeout });
301

302
  Future<void> startPolling() async {
303
    if (_timer == null) {
304
      deviceNotifier ??= ItemListNotifier<Device>();
305 306
      // Make initial population the default, fast polling timeout.
      _timer = _initTimer(null);
307 308 309
    }
  }

310
  Timer _initTimer(Duration pollingTimeout) {
311 312
    return Timer(_pollingInterval, () async {
      try {
313
        final List<Device> devices = await pollingGetDevices(timeout: pollingTimeout);
314
        deviceNotifier.updateWithNewList(devices);
315
      } on TimeoutException {
316
        globals.printTrace('Device poll timed out. Will retry.');
317
      }
318 319
      // Subsequent timeouts after initial population should wait longer.
      _timer = _initTimer(_pollingTimeout);
320 321 322
    });
  }

323
  Future<void> stopPolling() async {
324 325
    _timer?.cancel();
    _timer = null;
326 327
  }

328
  @override
329
  Future<List<Device>> get devices async {
330 331 332 333 334
    return _populateDevices();
  }

  @override
  Future<List<Device>> discoverDevices({ Duration timeout }) async {
335
    deviceNotifier = null;
336 337 338 339
    return _populateDevices(timeout: timeout);
  }

  Future<List<Device>> _populateDevices({ Duration timeout }) async {
340 341
    deviceNotifier ??= ItemListNotifier<Device>.from(await pollingGetDevices(timeout: timeout));
    return deviceNotifier.items;
342 343 344
  }

  Stream<Device> get onAdded {
345 346
    deviceNotifier ??= ItemListNotifier<Device>();
    return deviceNotifier.onAdded;
347 348 349
  }

  Stream<Device> get onRemoved {
350 351
    deviceNotifier ??= ItemListNotifier<Device>();
    return deviceNotifier.onRemoved;
352 353 354 355
  }

  void dispose() => stopPolling();

356
  @override
357 358 359
  String toString() => '$name device discovery';
}

360
abstract class Device {
361
  Device(this.id, {@required this.category, @required this.platformType, @required this.ephemeral});
362

363
  final String id;
364

365 366 367 368 369 370 371 372 373
  /// 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;

374 375
  String get name;

376 377
  bool get supportsStartPaused => true;

378
  /// Whether it is an emulated device running on localhost.
379
  Future<bool> get isLocalEmulator;
380

381 382 383 384 385 386 387 388
  /// 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;

389 390 391 392 393 394 395 396 397 398 399 400 401
  /// Whether the device is a simulator on a platform which supports hardware rendering.
  Future<bool> get supportsHardwareRendering async {
    assert(await isLocalEmulator);
    switch (await targetPlatform) {
      case TargetPlatform.android_arm:
      case TargetPlatform.android_arm64:
      case TargetPlatform.android_x64:
      case TargetPlatform.android_x86:
        return true;
      case TargetPlatform.ios:
      case TargetPlatform.darwin_x64:
      case TargetPlatform.linux_x64:
      case TargetPlatform.windows_x64:
402 403
      case TargetPlatform.fuchsia_arm64:
      case TargetPlatform.fuchsia_x64:
404 405 406 407 408
      default:
        return false;
    }
  }

409 410 411
  /// Whether the device is supported for the current project directory.
  bool isSupportedForProject(FlutterProject flutterProject);

412
  /// Check if a version of the given app is already installed
413
  Future<bool> isAppInstalled(covariant ApplicationPackage app);
414

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

418
  /// Install an app package on the current device
419
  Future<bool> installApp(covariant ApplicationPackage app);
420

421
  /// Uninstall an app package from the current device
422
  Future<bool> uninstallApp(covariant ApplicationPackage app);
423

424 425 426 427 428
  /// Check if the device is supported by Flutter
  bool isSupported();

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

431 432
  /// The device's platform.
  Future<TargetPlatform> get targetPlatform;
433

434
  Future<String> get sdkNameAndVersion;
435

436
  /// Get a log reader for this device.
437 438
  ///
  /// If `app` is specified, this will return a log reader specific to that
439
  /// application. Otherwise, a global log reader will be returned.
440 441 442 443 444 445 446 447
  ///
  /// 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,
  });
448

449 450 451
  /// Get the port forwarder for this device.
  DevicePortForwarder get portForwarder;

452 453
  /// Clear the device's logs.
  void clearLogs();
454

455 456 457
  /// Optional device-specific artifact overrides.
  OverrideArtifacts get artifactOverrides => null;

458 459 460
  /// Start an app package on the current device.
  ///
  /// [platformArgs] allows callers to pass platform-specific arguments to the
461
  /// start call. The build mode is not used by all platforms.
Devon Carew's avatar
Devon Carew committed
462
  Future<LaunchResult> startApp(
463
    covariant ApplicationPackage package, {
464 465
    String mainPath,
    String route,
Devon Carew's avatar
Devon Carew committed
466
    DebuggingOptions debuggingOptions,
467
    Map<String, dynamic> platformArgs,
468 469
    bool prebuiltApplication = false,
    bool ipv6 = false,
470
  });
471

472 473 474 475 476
  /// Whether this device implements support for hot reload.
  bool get supportsHotReload => true;

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

478 479
  /// Whether flutter applications running on this device can be terminated
  /// from the vmservice.
480
  bool get supportsFlutterExit => true;
481

482 483
  /// Whether the device supports taking screenshots of a running flutter
  /// application.
Devon Carew's avatar
Devon Carew committed
484 485
  bool get supportsScreenshot => false;

486 487 488
  /// Whether the device supports the '--fast-start' development mode.
  bool get supportsFastStart => false;

489
  /// Stop an app package on the current device.
490
  Future<bool> stopApp(covariant ApplicationPackage app);
491

492 493 494 495 496 497 498 499
  /// 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());
  }

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

502
  @nonVirtual
503
  @override
504
  // ignore: avoid_equals_and_hash_code_on_mutable_classes
505 506
  int get hashCode => id.hashCode;

507
  @nonVirtual
508
  @override
509
  // ignore: avoid_equals_and_hash_code_on_mutable_classes
510
  bool operator ==(Object other) {
511
    if (identical(this, other)) {
512
      return true;
513
    }
514 515
    return other is Device
        && other.id == id;
516 517
  }

518
  @override
519
  String toString() => name;
Devon Carew's avatar
Devon Carew committed
520

521
  static Stream<String> descriptions(List<Device> devices) async* {
522
    if (devices.isEmpty) {
523
      return;
524
    }
Devon Carew's avatar
Devon Carew committed
525

526
    // Extract device information
527
    final List<List<String>> table = <List<String>>[];
528
    for (final Device device in devices) {
Devon Carew's avatar
Devon Carew committed
529
      String supportIndicator = device.isSupported() ? '' : ' (unsupported)';
530 531 532
      final TargetPlatform targetPlatform = await device.targetPlatform;
      if (await device.isLocalEmulator) {
        final String type = targetPlatform == TargetPlatform.ios ? 'simulator' : 'emulator';
533 534
        supportIndicator += ' ($type)';
      }
535 536 537
      table.add(<String>[
        device.name,
        device.id,
538
        getNameForTargetPlatform(targetPlatform),
539
        '${await device.sdkNameAndVersion}$supportIndicator',
540 541 542 543
      ]);
    }

    // Calculate column widths
544
    final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i);
545
    List<int> widths = indices.map<int>((int i) => 0).toList();
546
    for (final List<String> row in table) {
547
      widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList();
548 549 550
    }

    // Join columns into lines of text
551
    for (final List<String> row in table) {
552
      yield indices.map<String>((int i) => row[i].padRight(widths[i])).join(' • ') + ' • ${row.last}';
553
    }
554 555
  }

556
  static Future<void> printDevices(List<Device> devices) async {
557
    await descriptions(devices).forEach(globals.printStatus);
Devon Carew's avatar
Devon Carew committed
558
  }
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  /// 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,
      }
    };
  }

582 583 584
  /// Clean up resources allocated by device
  ///
  /// For example log readers or port forwarders.
585
  Future<void> dispose();
586 587
}

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
/// 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
607
class DebuggingOptions {
608 609
  DebuggingOptions.enabled(
    this.buildInfo, {
610
    this.startPaused = false,
611
    this.disableServiceAuthCodes = false,
612
    this.dartFlags = '',
613 614 615
    this.enableSoftwareRendering = false,
    this.skiaDeterministicRendering = false,
    this.traceSkia = false,
616
    this.traceWhitelist,
617
    this.traceSystrace = false,
618
    this.endlessTraceBuffer = false,
619
    this.dumpSkpOnShaderCompilation = false,
620
    this.cacheSkSL = false,
621
    this.useTestFonts = false,
622
    this.verboseSystemLogs = false,
623 624
    this.hostVmServicePort,
    this.deviceVmServicePort,
625
    this.initializePlatform = true,
626 627
    this.hostname,
    this.port,
628
    this.webEnableExposeUrl,
629
    this.webUseSseForDebugProxy = true,
630 631
    this.webRunHeadless = false,
    this.webBrowserDebugPort,
632
    this.webEnableExpressionEvaluation = false,
633
    this.vmserviceOutFile,
634
    this.fastStart = false,
Devon Carew's avatar
Devon Carew committed
635 636
   }) : debuggingEnabled = true;

637 638 639 640 641
  DebuggingOptions.disabled(this.buildInfo, {
      this.initializePlatform = true,
      this.port,
      this.hostname,
      this.webEnableExposeUrl,
642
      this.webUseSseForDebugProxy = true,
643 644
      this.webRunHeadless = false,
      this.webBrowserDebugPort,
645
      this.cacheSkSL = false,
646
      this.traceWhitelist,
647
    }) : debuggingEnabled = false,
648 649
      useTestFonts = false,
      startPaused = false,
650
      dartFlags = '',
651
      disableServiceAuthCodes = false,
652 653 654 655
      enableSoftwareRendering = false,
      skiaDeterministicRendering = false,
      traceSkia = false,
      traceSystrace = false,
656
      endlessTraceBuffer = false,
657
      dumpSkpOnShaderCompilation = false,
658
      verboseSystemLogs = false,
659 660
      hostVmServicePort = null,
      deviceVmServicePort = null,
661
      vmserviceOutFile = null,
662 663
      fastStart = false,
      webEnableExpressionEvaluation = false;
Devon Carew's avatar
Devon Carew committed
664 665 666

  final bool debuggingEnabled;

667
  final BuildInfo buildInfo;
Devon Carew's avatar
Devon Carew committed
668
  final bool startPaused;
669
  final String dartFlags;
670
  final bool disableServiceAuthCodes;
671
  final bool enableSoftwareRendering;
672
  final bool skiaDeterministicRendering;
673
  final bool traceSkia;
674
  final String traceWhitelist;
675
  final bool traceSystrace;
676
  final bool endlessTraceBuffer;
677
  final bool dumpSkpOnShaderCompilation;
678
  final bool cacheSkSL;
679
  final bool useTestFonts;
680
  final bool verboseSystemLogs;
681 682
  /// Whether to invoke webOnlyInitializePlatform in Flutter for web.
  final bool initializePlatform;
683 684
  final int hostVmServicePort;
  final int deviceVmServicePort;
685 686
  final String port;
  final String hostname;
687
  final bool webEnableExposeUrl;
688
  final bool webUseSseForDebugProxy;
689 690 691 692 693 694 695 696 697 698 699

  /// 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;

700 701 702
  /// Enable expression evaluation for web target
  final bool webEnableExpressionEvaluation;

703
  /// A file where the vmservice URL should be written after the application is started.
704
  final String vmserviceOutFile;
705
  final bool fastStart;
Devon Carew's avatar
Devon Carew committed
706

707
  bool get hasObservatoryPort => hostVmServicePort != null;
Devon Carew's avatar
Devon Carew committed
708 709 710
}

class LaunchResult {
711
  LaunchResult.succeeded({ this.observatoryUri }) : started = true;
712 713 714
  LaunchResult.failed()
    : started = false,
      observatoryUri = null;
Devon Carew's avatar
Devon Carew committed
715

716
  bool get hasObservatory => observatoryUri != null;
Devon Carew's avatar
Devon Carew committed
717 718

  final bool started;
719
  final Uri observatoryUri;
Devon Carew's avatar
Devon Carew committed
720 721 722

  @override
  String toString() {
723
    final StringBuffer buf = StringBuffer('started=$started');
724
    if (observatoryUri != null) {
725
      buf.write(', observatory=$observatoryUri');
726
    }
Devon Carew's avatar
Devon Carew committed
727 728 729 730
    return buf.toString();
  }
}

731
class ForwardedPort {
732 733
  ForwardedPort(this.hostPort, this.devicePort) : context = null;
  ForwardedPort.withContext(this.hostPort, this.devicePort, this.context);
734 735 736

  final int hostPort;
  final int devicePort;
737
  final Process context;
738

739
  @override
740
  String toString() => 'ForwardedPort HOST:$hostPort to DEVICE:$devicePort';
741 742 743

  /// Kill subprocess (if present) used in forwarding.
  void dispose() {
744 745
    if (context != null) {
      context.kill();
746 747
    }
  }
748 749 750 751 752 753 754 755 756
}

/// 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.
757
  /// If [hostPort] is null or zero, will auto select a host port.
758
  /// Returns a Future that completes with the host port.
759
  Future<int> forward(int devicePort, { int hostPort });
760 761

  /// Stops forwarding [forwardedPort].
762
  Future<void> unforward(ForwardedPort forwardedPort);
763 764

  /// Cleanup allocated resources, like forwardedPorts
765
  Future<void> dispose();
766 767
}

Devon Carew's avatar
Devon Carew committed
768
/// Read the log for a particular device.
Devon Carew's avatar
Devon Carew committed
769 770 771
abstract class DeviceLogReader {
  String get name;

Devon Carew's avatar
Devon Carew committed
772 773
  /// 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
774

775 776
  /// Some logs can be obtained from a VM service stream.
  /// Set this after the VM services are connected.
777
  vm_service.VmService connectedVMService;
778

779
  @override
Devon Carew's avatar
Devon Carew committed
780
  String toString() => name;
781

782
  /// Process ID of the app on the device.
783
  int appPid;
784 785

  // Clean up resources allocated by log reader e.g. subprocesses
786
  void dispose();
Devon Carew's avatar
Devon Carew committed
787
}
788 789 790

/// Describes an app running on the device.
class DiscoveredApp {
791
  DiscoveredApp(this.id, this.observatoryPort);
792 793 794
  final String id;
  final int observatoryPort;
}
795 796 797 798 799 800 801 802 803 804 805

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

  @override
  final String name;

  @override
  int appPid;

806
  @override
807
  vm_service.VmService connectedVMService;
808

809 810
  @override
  Stream<String> get logLines => const Stream<String>.empty();
811 812 813

  @override
  void dispose() { }
814 815 816 817 818 819 820
}

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

  @override
821
  Future<int> forward(int devicePort, { int hostPort }) async => devicePort;
822 823 824 825 826

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

  @override
827
  Future<void> unforward(ForwardedPort forwardedPort) async { }
828 829 830

  @override
  Future<void> dispose() async { }
831
}