device.dart 22.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 9
import 'package:meta/meta.dart';

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

31
DeviceManager get deviceManager => context.get<DeviceManager>();
32

33 34 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
/// 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;
}

65 66
/// A class to get all available devices.
class DeviceManager {
67

68
  /// Constructing DeviceManagers is cheap; they only do expensive work if some
69
  /// of their methods are called.
70 71 72 73 74 75 76
  List<DeviceDiscovery> get deviceDiscoverers => _deviceDiscoverers;
  final List<DeviceDiscovery> _deviceDiscoverers = List<DeviceDiscovery>.unmodifiable(<DeviceDiscovery>[
    AndroidDevices(),
    IOSDevices(),
    IOSSimulators(),
    FuchsiaDevices(),
    FlutterTesterDevices(),
77
    MacOSDevices(),
78 79 80 81
    LinuxDevices(
      platform: globals.platform,
      featureFlags: featureFlags,
    ),
82 83 84
    WindowsDevices(),
    WebDevices(),
  ]);
85

86 87
  String _specifiedDeviceId;

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

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

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

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

107 108
  Future<List<Device>> getDevicesById(String deviceId) async {
    final List<Device> devices = await getAllConnectedDevices();
Devon Carew's avatar
Devon Carew committed
109
    deviceId = deviceId.toLowerCase();
110 111 112 113 114 115 116
    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);

117 118
    final Device exactMatch = devices.firstWhere(
        exactlyMatchesDeviceId, orElse: () => null);
119
    if (exactMatch != null) {
120
      return <Device>[exactMatch];
121
    }
122

123
    // Match on a id or name starting with [deviceId].
124
    return devices.where(startsWithDeviceId).toList();
Devon Carew's avatar
Devon Carew committed
125 126
  }

127
  /// Return the list of connected devices, filtered by any user-specified device id.
128
  Future<List<Device>> getDevices() {
129 130 131
    return hasSpecifiedDeviceId
        ? getDevicesById(specifiedDeviceId)
        : getAllConnectedDevices();
132 133
  }

134
  Iterable<DeviceDiscovery> get _platformDiscoverers {
135
    return deviceDiscoverers.where((DeviceDiscovery discoverer) => discoverer.supportsPlatform);
136 137
  }

138
  /// Return the list of all connected devices.
139 140 141 142 143 144 145
  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();
146
  }
147 148 149 150 151 152 153 154

  /// 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 {
155
    return <String>[
156
      for (final DeviceDiscovery discoverer in _platformDiscoverers)
157 158
        ...await discoverer.getDiagnostics(),
    ];
159
  }
160 161 162

  /// Find and return a list of devices based on the current project and environment.
  ///
163
  /// Returns a list of devices specified by the user.
164 165 166 167 168 169 170 171 172 173
  ///
  /// * 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.
174
  Future<List<Device>> findTargetDevices(FlutterProject flutterProject) async {
175
    List<Device> devices = await getDevices();
176

177 178 179 180 181 182
    // 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>[
183
        for (final Device device in devices)
184 185
          if (await device.targetPlatform != TargetPlatform.fuchsia_arm64 &&
              await device.targetPlatform != TargetPlatform.fuchsia_x64 &&
186
              await device.targetPlatform != TargetPlatform.web_javascript)
187
            device,
188 189 190 191 192 193 194 195
      ];
    }

    // 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>[
196
        for (final Device device in devices)
197
          if (isDeviceSupportedForProject(device, flutterProject))
198
            device,
199
      ];
200 201 202 203 204 205
    } 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>[];
206
    }
207

208 209 210 211 212
    // 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) {
213 214 215 216 217 218 219 220 221 222 223 224
      // 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.
225
  ///
226
  /// This exists to allow the check to be overridden for google3 clients.
227 228 229
  bool isDeviceSupportedForProject(Device device, FlutterProject flutterProject) {
    return device.isSupportedForProject(flutterProject);
  }
230 231 232 233 234
}

/// An abstract class to discover and enumerate a specific type of devices.
abstract class DeviceDiscovery {
  bool get supportsPlatform;
235 236 237 238 239

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

240
  Future<List<Device>> get devices;
241 242 243

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

247 248 249 250 251
/// A [DeviceDiscovery] implementation that uses polling to discover device adds
/// and removals.
abstract class PollingDeviceDiscovery extends DeviceDiscovery {
  PollingDeviceDiscovery(this.name);

252 253
  static const Duration _pollingInterval = Duration(seconds: 4);
  static const Duration _pollingTimeout = Duration(seconds: 30);
254 255 256

  final String name;
  ItemListNotifier<Device> _items;
257
  Timer _timer;
258

259
  Future<List<Device>> pollingGetDevices();
260 261

  void startPolling() {
262
    if (_timer == null) {
263
      _items ??= ItemListNotifier<Device>();
264
      _timer = _initTimer();
265 266 267
    }
  }

268 269 270 271 272 273
  Timer _initTimer() {
    return Timer(_pollingInterval, () async {
      try {
        final List<Device> devices = await pollingGetDevices().timeout(_pollingTimeout);
        _items.updateWithNewList(devices);
      } on TimeoutException {
274
        globals.printTrace('Device poll timed out. Will retry.');
275 276 277 278 279
      }
      _timer = _initTimer();
    });
  }

280
  void stopPolling() {
281 282
    _timer?.cancel();
    _timer = null;
283 284
  }

285
  @override
286
  Future<List<Device>> get devices async {
287
    _items ??= ItemListNotifier<Device>.from(await pollingGetDevices());
288 289 290 291
    return _items.items;
  }

  Stream<Device> get onAdded {
292
    _items ??= ItemListNotifier<Device>();
293 294 295 296
    return _items.onAdded;
  }

  Stream<Device> get onRemoved {
297
    _items ??= ItemListNotifier<Device>();
298 299 300 301 302
    return _items.onRemoved;
  }

  void dispose() => stopPolling();

303
  @override
304 305 306
  String toString() => '$name device discovery';
}

307
abstract class Device {
308
  Device(this.id, {@required this.category, @required this.platformType, @required this.ephemeral});
309

310
  final String id;
311

312 313 314 315 316 317 318 319 320
  /// 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;

321 322
  String get name;

323 324
  bool get supportsStartPaused => true;

325
  /// Whether it is an emulated device running on localhost.
326
  Future<bool> get isLocalEmulator;
327

328 329 330 331 332 333 334 335
  /// 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;

336 337 338 339 340 341 342 343 344 345 346 347 348
  /// 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:
349 350
      case TargetPlatform.fuchsia_arm64:
      case TargetPlatform.fuchsia_x64:
351 352 353 354 355
      default:
        return false;
    }
  }

356 357 358
  /// Whether the device is supported for the current project directory.
  bool isSupportedForProject(FlutterProject flutterProject);

359
  /// Check if a version of the given app is already installed
360
  Future<bool> isAppInstalled(covariant ApplicationPackage app);
361

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

365
  /// Install an app package on the current device
366
  Future<bool> installApp(covariant ApplicationPackage app);
367

368
  /// Uninstall an app package from the current device
369
  Future<bool> uninstallApp(covariant ApplicationPackage app);
370

371 372 373 374 375
  /// 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.
376
  String supportMessage() => isSupported() ? 'Supported' : 'Unsupported';
377

378 379
  /// The device's platform.
  Future<TargetPlatform> get targetPlatform;
380

381
  Future<String> get sdkNameAndVersion;
382

383 384 385
  /// Get a log reader for this device.
  /// If [app] is specified, this will return a log reader specific to that
  /// application. Otherwise, a global log reader will be returned.
386
  DeviceLogReader getLogReader({ covariant ApplicationPackage app });
387

388 389 390
  /// Get the port forwarder for this device.
  DevicePortForwarder get portForwarder;

391 392
  /// Clear the device's logs.
  void clearLogs();
393

394 395 396
  /// Optional device-specific artifact overrides.
  OverrideArtifacts get artifactOverrides => null;

397 398 399
  /// Start an app package on the current device.
  ///
  /// [platformArgs] allows callers to pass platform-specific arguments to the
400
  /// start call. The build mode is not used by all platforms.
Devon Carew's avatar
Devon Carew committed
401
  Future<LaunchResult> startApp(
402
    covariant ApplicationPackage package, {
403 404
    String mainPath,
    String route,
Devon Carew's avatar
Devon Carew committed
405
    DebuggingOptions debuggingOptions,
406
    Map<String, dynamic> platformArgs,
407 408
    bool prebuiltApplication = false,
    bool ipv6 = false,
409
  });
410

411 412 413 414 415
  /// Whether this device implements support for hot reload.
  bool get supportsHotReload => true;

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

417 418
  /// Whether flutter applications running on this device can be terminated
  /// from the vmservice.
419
  bool get supportsFlutterExit => true;
420

421 422
  /// Whether the device supports taking screenshots of a running flutter
  /// application.
Devon Carew's avatar
Devon Carew committed
423 424
  bool get supportsScreenshot => false;

425 426 427
  /// Whether the device supports the '--fast-start' development mode.
  bool get supportsFastStart => false;

428
  /// Stop an app package on the current device.
429
  Future<bool> stopApp(covariant ApplicationPackage app);
430

431 432 433 434 435 436 437 438
  /// 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());
  }

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

441
  @override
442 443
  int get hashCode => id.hashCode;

444
  @override
445
  bool operator ==(Object other) {
446
    if (identical(this, other)) {
447
      return true;
448
    }
449 450
    return other is Device
        && other.id == id;
451 452
  }

453
  @override
454
  String toString() => name;
Devon Carew's avatar
Devon Carew committed
455

456
  static Stream<String> descriptions(List<Device> devices) async* {
457
    if (devices.isEmpty) {
458
      return;
459
    }
Devon Carew's avatar
Devon Carew committed
460

461
    // Extract device information
462
    final List<List<String>> table = <List<String>>[];
463
    for (final Device device in devices) {
Devon Carew's avatar
Devon Carew committed
464
      String supportIndicator = device.isSupported() ? '' : ' (unsupported)';
465 466 467
      final TargetPlatform targetPlatform = await device.targetPlatform;
      if (await device.isLocalEmulator) {
        final String type = targetPlatform == TargetPlatform.ios ? 'simulator' : 'emulator';
468 469
        supportIndicator += ' ($type)';
      }
470 471 472
      table.add(<String>[
        device.name,
        device.id,
473
        getNameForTargetPlatform(targetPlatform),
474
        '${await device.sdkNameAndVersion}$supportIndicator',
475 476 477 478
      ]);
    }

    // Calculate column widths
479
    final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i);
480
    List<int> widths = indices.map<int>((int i) => 0).toList();
481
    for (final List<String> row in table) {
482
      widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList();
483 484 485
    }

    // Join columns into lines of text
486
    for (final List<String> row in table) {
487
      yield indices.map<String>((int i) => row[i].padRight(widths[i])).join(' • ') + ' • ${row.last}';
488
    }
489 490
  }

491
  static Future<void> printDevices(List<Device> devices) async {
492
    await descriptions(devices).forEach(globals.printStatus);
Devon Carew's avatar
Devon Carew committed
493
  }
494 495 496 497

  /// Clean up resources allocated by device
  ///
  /// For example log readers or port forwarders.
498
  Future<void> dispose();
499 500
}

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
/// 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
520
class DebuggingOptions {
521 522
  DebuggingOptions.enabled(
    this.buildInfo, {
523
    this.startPaused = false,
524
    this.disableServiceAuthCodes = false,
525
    this.dartFlags = '',
526 527 528
    this.enableSoftwareRendering = false,
    this.skiaDeterministicRendering = false,
    this.traceSkia = false,
529
    this.traceSystrace = false,
530
    this.endlessTraceBuffer = false,
531
    this.dumpSkpOnShaderCompilation = false,
532
    this.cacheSkSL = false,
533
    this.useTestFonts = false,
534
    this.verboseSystemLogs = false,
535 536
    this.hostVmServicePort,
    this.deviceVmServicePort,
537
    this.initializePlatform = true,
538 539
    this.hostname,
    this.port,
540
    this.webEnableExposeUrl,
541 542
    this.webRunHeadless = false,
    this.webBrowserDebugPort,
543
    this.vmserviceOutFile,
544
    this.fastStart = false,
Devon Carew's avatar
Devon Carew committed
545 546
   }) : debuggingEnabled = true;

547 548 549 550 551
  DebuggingOptions.disabled(this.buildInfo, {
      this.initializePlatform = true,
      this.port,
      this.hostname,
      this.webEnableExposeUrl,
552 553
      this.webRunHeadless = false,
      this.webBrowserDebugPort,
554 555
      this.cacheSkSL = false,
    }) : debuggingEnabled = false,
556 557
      useTestFonts = false,
      startPaused = false,
558
      dartFlags = '',
559
      disableServiceAuthCodes = false,
560 561 562 563
      enableSoftwareRendering = false,
      skiaDeterministicRendering = false,
      traceSkia = false,
      traceSystrace = false,
564
      endlessTraceBuffer = false,
565
      dumpSkpOnShaderCompilation = false,
566
      verboseSystemLogs = false,
567 568
      hostVmServicePort = null,
      deviceVmServicePort = null,
569 570
      vmserviceOutFile = null,
      fastStart = false;
Devon Carew's avatar
Devon Carew committed
571 572 573

  final bool debuggingEnabled;

574
  final BuildInfo buildInfo;
Devon Carew's avatar
Devon Carew committed
575
  final bool startPaused;
576
  final String dartFlags;
577
  final bool disableServiceAuthCodes;
578
  final bool enableSoftwareRendering;
579
  final bool skiaDeterministicRendering;
580
  final bool traceSkia;
581
  final bool traceSystrace;
582
  final bool endlessTraceBuffer;
583
  final bool dumpSkpOnShaderCompilation;
584
  final bool cacheSkSL;
585
  final bool useTestFonts;
586
  final bool verboseSystemLogs;
587 588
  /// Whether to invoke webOnlyInitializePlatform in Flutter for web.
  final bool initializePlatform;
589 590
  final int hostVmServicePort;
  final int deviceVmServicePort;
591 592
  final String port;
  final String hostname;
593
  final bool webEnableExposeUrl;
594 595 596 597 598 599 600 601 602 603 604

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

605
  /// A file where the vmservice URL should be written after the application is started.
606
  final String vmserviceOutFile;
607
  final bool fastStart;
Devon Carew's avatar
Devon Carew committed
608

609
  bool get hasObservatoryPort => hostVmServicePort != null;
Devon Carew's avatar
Devon Carew committed
610 611 612
}

class LaunchResult {
613
  LaunchResult.succeeded({ this.observatoryUri }) : started = true;
614 615 616
  LaunchResult.failed()
    : started = false,
      observatoryUri = null;
Devon Carew's avatar
Devon Carew committed
617

618
  bool get hasObservatory => observatoryUri != null;
Devon Carew's avatar
Devon Carew committed
619 620

  final bool started;
621
  final Uri observatoryUri;
Devon Carew's avatar
Devon Carew committed
622 623 624

  @override
  String toString() {
625
    final StringBuffer buf = StringBuffer('started=$started');
626
    if (observatoryUri != null) {
627
      buf.write(', observatory=$observatoryUri');
628
    }
Devon Carew's avatar
Devon Carew committed
629 630 631 632
    return buf.toString();
  }
}

633
class ForwardedPort {
634 635
  ForwardedPort(this.hostPort, this.devicePort) : context = null;
  ForwardedPort.withContext(this.hostPort, this.devicePort, this.context);
636 637 638

  final int hostPort;
  final int devicePort;
639
  final Process context;
640

641
  @override
642
  String toString() => 'ForwardedPort HOST:$hostPort to DEVICE:$devicePort';
643 644 645

  /// Kill subprocess (if present) used in forwarding.
  void dispose() {
646 647
    if (context != null) {
      context.kill();
648 649
    }
  }
650 651 652 653 654 655 656 657 658
}

/// 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.
659
  /// If [hostPort] is null or zero, will auto select a host port.
660
  /// Returns a Future that completes with the host port.
661
  Future<int> forward(int devicePort, { int hostPort });
662 663

  /// Stops forwarding [forwardedPort].
664
  Future<void> unforward(ForwardedPort forwardedPort);
665 666

  /// Cleanup allocated resources, like forwardedPorts
667
  Future<void> dispose();
668 669
}

Devon Carew's avatar
Devon Carew committed
670
/// Read the log for a particular device.
Devon Carew's avatar
Devon Carew committed
671 672 673
abstract class DeviceLogReader {
  String get name;

Devon Carew's avatar
Devon Carew committed
674 675
  /// 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
676

677 678
  /// Some logs can be obtained from a VM service stream.
  /// Set this after the VM services are connected.
679
  VMService connectedVMService;
680

681
  @override
Devon Carew's avatar
Devon Carew committed
682
  String toString() => name;
683

684
  /// Process ID of the app on the device.
685
  int appPid;
686 687

  // Clean up resources allocated by log reader e.g. subprocesses
688
  void dispose();
Devon Carew's avatar
Devon Carew committed
689
}
690 691 692

/// Describes an app running on the device.
class DiscoveredApp {
693
  DiscoveredApp(this.id, this.observatoryPort);
694 695 696
  final String id;
  final int observatoryPort;
}
697 698 699 700 701 702 703 704 705 706 707

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

  @override
  final String name;

  @override
  int appPid;

708
  @override
709
  VMService connectedVMService;
710

711 712
  @override
  Stream<String> get logLines => const Stream<String>.empty();
713 714 715

  @override
  void dispose() { }
716 717 718 719 720 721 722
}

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

  @override
723
  Future<int> forward(int devicePort, { int hostPort }) async => devicePort;
724 725 726 727 728

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

  @override
729
  Future<void> unforward(ForwardedPort forwardedPort) async { }
730 731 732

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