resident_runner.dart 27.2 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

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

9
import 'android/gradle.dart';
10
import 'application_package.dart';
11
import 'artifacts.dart';
12
import 'asset.dart';
13
import 'base/common.dart';
14 15
import 'base/file_system.dart';
import 'base/io.dart';
16
import 'base/logger.dart';
17
import 'base/terminal.dart';
18
import 'base/utils.dart';
19
import 'build_info.dart';
20
import 'compile.dart';
21 22 23
import 'dart/dependencies.dart';
import 'dart/package_map.dart';
import 'dependency_checker.dart';
24
import 'devfs.dart';
25 26
import 'device.dart';
import 'globals.dart';
27 28
import 'run_cold.dart';
import 'run_hot.dart';
29
import 'vmservice.dart';
30

31 32 33 34 35 36
class FlutterDevice {
  final Device device;
  List<Uri> observatoryUris;
  List<VMService> vmServices;
  DevFS devFS;
  ApplicationPackage package;
37
  ResidentCompiler generator;
38 39 40

  StreamSubscription<String> _loggingSubscription;

41 42 43 44 45
  FlutterDevice(this.device, { bool previewDart2 : false }) {
    if (previewDart2)
      generator = new ResidentCompiler(
        artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath));
  }
46

47
  String viewFilter;
48

49 50 51 52 53 54 55
  /// If the [reloadSources] parameter is not null the 'reloadSources' service
  /// will be registered.
  /// The 'reloadSources' service can be used by other Service Protocol clients
  /// connected to the VM (e.g. Observatory) to request a reload of the source
  /// code of the running application (a.k.a. HotReload).
  /// This ensures that the reload process follows the normal orchestration of
  /// the Flutter Tools and not just the VM internal service.
56
  Future<Null> _connect({ReloadSources reloadSources}) async {
57 58 59 60
    if (vmServices != null)
      return;
    vmServices = new List<VMService>(observatoryUris.length);
    for (int i = 0; i < observatoryUris.length; i++) {
61
      printTrace('Connecting to service protocol: ${observatoryUris[i]}');
62
      vmServices[i] = await VMService.connect(observatoryUris[i],
63
          reloadSources: reloadSources);
64
      printTrace('Successfully connected to service protocol: ${observatoryUris[i]}');
65 66 67 68
    }
  }

  Future<Null> refreshViews() async {
69
    if (vmServices == null || vmServices.isEmpty)
70 71 72 73 74 75
      return;
    for (VMService service in vmServices)
      await service.vm.refreshViews();
  }

  List<FlutterView> get views {
76 77 78 79 80 81 82 83 84
    if (vmServices == null)
      return <FlutterView>[];

    return vmServices
      .where((VMService service) => !service.isClosed)
      .expand((VMService service) => viewFilter != null
          ? service.vm.allViewsWithName(viewFilter)
          : service.vm.views)
      .toList();
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  }

  Future<Null> getVMs() async {
    for (VMService service in vmServices)
      await service.getVM();
  }

  Future<Null> waitForViews() async {
    // Refresh the view list, and wait a bit for the list to populate.
    for (VMService service in vmServices)
      await service.waitForViews();
  }

  Future<Null> stopApps() async {
    final List<FlutterView> flutterViews = views;
    if (flutterViews == null || flutterViews.isEmpty)
      return;
    for (FlutterView view in flutterViews) {
103 104 105 106
      if (view != null && view.uiIsolate != null) {
        // Manage waits specifically below.
        view.uiIsolate.flutterExit(); // ignore: unawaited_futures
      }
107 108 109 110 111
    }
    await new Future<Null>.delayed(const Duration(milliseconds: 100));
  }

  Future<Uri> setupDevFS(String fsName,
112 113 114
    Directory rootDirectory, {
    String packagesFilePath
  }) {
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
    // One devFS per device. Shared by all running instances.
    devFS = new DevFS(
      vmServices[0],
      fsName,
      rootDirectory,
      packagesFilePath: packagesFilePath
    );
    return devFS.create();
  }

  List<Future<Map<String, dynamic>>> reloadSources(
    String entryPath, {
    bool pause: false
  }) {
    final Uri deviceEntryUri = devFS.baseUri.resolveUri(fs.path.toUri(entryPath));
    final Uri devicePackagesUri = devFS.baseUri.resolve('.packages');
    final List<Future<Map<String, dynamic>>> reports = <Future<Map<String, dynamic>>>[];
    for (FlutterView view in views) {
      final Future<Map<String, dynamic>> report = view.uiIsolate.reloadSources(
        pause: pause,
        rootLibUri: deviceEntryUri,
        packagesUri: devicePackagesUri
      );
      reports.add(report);
    }
    return reports;
  }

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  // Lists program elements changed in the most recent reload that have not
  // since executed.
  Future<List<ProgramElement>> unusedChangesInLastReload() async {
    final List<Future<List<ProgramElement>>> reports =
      <Future<List<ProgramElement>>>[];
    for (FlutterView view in views)
      reports.add(view.uiIsolate.getUnusedChangesInLastReload());
    final List<ProgramElement> elements = <ProgramElement>[];
    for (Future<List<ProgramElement>> report in reports) {
      for (ProgramElement element in await report)
        elements.add(new ProgramElement(element.qualifiedName,
                                        devFS.deviceUriToHostUri(element.uri),
                                        element.line,
                                        element.column));
    }
    return elements;
  }

161 162 163 164 165 166 167 168 169 170
  Future<Null> debugDumpApp() async {
    for (FlutterView view in views)
      await view.uiIsolate.flutterDebugDumpApp();
  }

  Future<Null> debugDumpRenderTree() async {
    for (FlutterView view in views)
      await view.uiIsolate.flutterDebugDumpRenderTree();
  }

171 172 173 174 175
  Future<Null> debugDumpLayerTree() async {
    for (FlutterView view in views)
      await view.uiIsolate.flutterDebugDumpLayerTree();
  }

176
  Future<Null> debugDumpSemanticsTreeInTraversalOrder() async {
177
    for (FlutterView view in views)
178 179 180 181 182 183
      await view.uiIsolate.flutterDebugDumpSemanticsTreeInTraversalOrder();
  }

  Future<Null> debugDumpSemanticsTreeInInverseHitTestOrder() async {
    for (FlutterView view in views)
      await view.uiIsolate.flutterDebugDumpSemanticsTreeInInverseHitTestOrder();
184 185
  }

186 187 188 189 190
  Future<Null> toggleDebugPaintSizeEnabled() async {
    for (FlutterView view in views)
      await view.uiIsolate.flutterToggleDebugPaintSizeEnabled();
  }

191 192 193 194 195
  Future<Null> debugTogglePerformanceOverlayOverride() async {
    for (FlutterView view in views)
      await view.uiIsolate.flutterTogglePerformanceOverlayOverride();
  }

196 197 198 199 200
  Future<Null> toggleWidgetInspector() async {
    for (FlutterView view in views)
      await view.uiIsolate.flutterToggleWidgetInspector();
  }

201
  Future<String> togglePlatform({ String from }) async {
202 203 204 205 206 207 208 209 210 211
    String to;
    switch (from) {
      case 'iOS':
        to = 'android';
        break;
      case 'android':
      default:
        to = 'iOS';
        break;
    }
212
    for (FlutterView view in views)
213 214 215 216 217 218 219 220
      await view.uiIsolate.flutterPlatformOverride(to);
    return to;
  }

  void startEchoingDeviceLog() {
    if (_loggingSubscription != null)
      return;
    _loggingSubscription = device.getLogReader(app: package).logLines.listen((String line) {
221
      if (!line.contains('Observatory listening on http'))
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        printStatus(line);
    });
  }

  Future<Null> stopEchoingDeviceLog() async {
    if (_loggingSubscription == null)
      return;
    await _loggingSubscription.cancel();
    _loggingSubscription = null;
  }

  void initLogReader() {
    device.getLogReader(app: package).appPid = vmServices.first.vm.pid;
  }

  Future<int> runHot({
    HotRunner hotRunner,
    String route,
    bool shouldBuild,
  }) async {
    final bool prebuiltMode = hotRunner.applicationBinary != null;
243
    final String modeName = hotRunner.debuggingOptions.buildInfo.modeName;
244 245 246
    printStatus('Launching ${getDisplayPath(hotRunner.mainPath)} on ${device.name} in $modeName mode...');

    final TargetPlatform targetPlatform = await device.targetPlatform;
247
    package = await getApplicationPackageForPlatform(
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
      targetPlatform,
      applicationBinary: hotRunner.applicationBinary
    );

    if (package == null) {
      String message = 'No application found for $targetPlatform.';
      final String hint = getMissingPackageHintForPlatform(targetPlatform);
      if (hint != null)
        message += '\n$hint';
      printError(message);
      return 1;
    }

    final Map<String, dynamic> platformArgs = <String, dynamic>{};

    startEchoingDeviceLog();

    // Start the application.
    final bool hasDirtyDependencies = hotRunner.hasDirtyDependencies(this);
    final Future<LaunchResult> futureResult = device.startApp(
      package,
      mainPath: hotRunner.mainPath,
      debuggingOptions: hotRunner.debuggingOptions,
      platformArgs: platformArgs,
      route: route,
      prebuiltApplication: prebuiltMode,
274 275
      applicationNeedsRebuild: shouldBuild || hasDirtyDependencies,
      usesTerminalUi: hotRunner.usesTerminalUI,
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    );

    final LaunchResult result = await futureResult;

    if (!result.started) {
      printError('Error launching application on ${device.name}.');
      await stopEchoingDeviceLog();
      return 2;
    }
    observatoryUris = <Uri>[result.observatoryUri];
    return 0;
  }


  Future<int> runCold({
    ColdRunner coldRunner,
    String route,
    bool shouldBuild: true,
  }) async {
    final TargetPlatform targetPlatform = await device.targetPlatform;
296
    package = await getApplicationPackageForPlatform(
297 298 299 300
      targetPlatform,
      applicationBinary: coldRunner.applicationBinary
    );

301
    final String modeName = coldRunner.debuggingOptions.buildInfo.modeName;
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    final bool prebuiltMode = coldRunner.applicationBinary != null;
    if (coldRunner.mainPath == null) {
      assert(prebuiltMode);
      printStatus('Launching ${package.displayName} on ${device.name} in $modeName mode...');
    } else {
      printStatus('Launching ${getDisplayPath(coldRunner.mainPath)} on ${device.name} in $modeName mode...');
    }

    if (package == null) {
      String message = 'No application found for $targetPlatform.';
      final String hint = getMissingPackageHintForPlatform(targetPlatform);
      if (hint != null)
        message += '\n$hint';
      printError(message);
      return 1;
    }

    Map<String, dynamic> platformArgs;
    if (coldRunner.traceStartup != null)
      platformArgs = <String, dynamic>{ 'trace-startup': coldRunner.traceStartup };

    startEchoingDeviceLog();

    final bool hasDirtyDependencies = coldRunner.hasDirtyDependencies(this);
    final LaunchResult result = await device.startApp(
      package,
      mainPath: coldRunner.mainPath,
      debuggingOptions: coldRunner.debuggingOptions,
      platformArgs: platformArgs,
      route: route,
      prebuiltApplication: prebuiltMode,
333 334
      applicationNeedsRebuild: shouldBuild || hasDirtyDependencies,
      usesTerminalUi: coldRunner.usesTerminalUI,
335 336 337 338 339 340 341 342 343 344 345 346 347
    );

    if (!result.started) {
      printError('Error running application on ${device.name}.');
      await stopEchoingDeviceLog();
      return 2;
    }
    if (result.hasObservatory)
      observatoryUris = <Uri>[result.observatoryUri];
    return 0;
  }

  Future<bool> updateDevFS({
348 349
    String mainPath,
    String target,
350 351
    AssetBundle bundle,
    bool bundleDirty: false,
352 353
    Set<String> fileFilter,
    bool fullRestart: false
354 355 356 357 358 359 360 361
  }) async {
    final Status devFSStatus = logger.startProgress(
      'Syncing files to device ${device.name}...',
      expectSlowOperation: true
    );
    int bytes = 0;
    try {
      bytes = await devFS.update(
362 363
        mainPath: mainPath,
        target: target,
364 365
        bundle: bundle,
        bundleDirty: bundleDirty,
366
        fileFilter: fileFilter,
367 368
        generator: generator,
        fullRestart: fullRestart
369 370 371 372 373 374 375 376 377
      );
    } on DevFSException {
      devFSStatus.cancel();
      return false;
    }
    devFSStatus.stop();
    printTrace('Synced ${getSizeAsMB(bytes)}.');
    return true;
  }
378 379 380 381 382 383 384

  void updateReloadStatus(bool wasReloadSuccessful) {
    if (wasReloadSuccessful)
      generator?.accept();
    else
      generator?.reject();
  }
385 386
}

387 388
// Shared code between different resident application runners.
abstract class ResidentRunner {
389
  ResidentRunner(this.flutterDevices, {
390 391
    this.target,
    this.debuggingOptions,
392 393 394 395
    this.usesTerminalUI: true,
    String projectRootPath,
    String packagesFilePath,
    String projectAssets,
396
    this.stayResident,
397 398
  }) {
    _mainPath = findMainDartFile(target);
399
    _projectRootPath = projectRootPath ?? fs.currentDirectory.path;
400
    _packagesFilePath =
401
        packagesFilePath ?? fs.path.absolute(PackageMap.globalPackagesPath);
402 403 404 405 406
    if (projectAssets != null)
      _assetBundle = new AssetBundle.fixed(_projectRootPath, projectAssets);
    else
      _assetBundle = new AssetBundle();
  }
407

408
  final List<FlutterDevice> flutterDevices;
409 410 411
  final String target;
  final DebuggingOptions debuggingOptions;
  final bool usesTerminalUI;
412
  final bool stayResident;
413
  final Completer<int> _finished = new Completer<int>();
414
  bool _stopped = false;
415 416 417 418 419 420 421 422
  String _packagesFilePath;
  String get packagesFilePath => _packagesFilePath;
  String _projectRootPath;
  String get projectRootPath => _projectRootPath;
  String _mainPath;
  String get mainPath => _mainPath;
  AssetBundle _assetBundle;
  AssetBundle get assetBundle => _assetBundle;
423

424 425 426
  bool get isRunningDebug => debuggingOptions.buildInfo.isDebug;
  bool get isRunningProfile => debuggingOptions.buildInfo.isProfile;
  bool get isRunningRelease => debuggingOptions.buildInfo.isRelease;
427 428
  bool get supportsServiceProtocol => isRunningDebug || isRunningProfile;

429
  /// Start the app and keep the process running during its lifetime.
430
  Future<int> run({
431
    Completer<DebugConnectionInfo> connectionInfoCompleter,
432
    Completer<Null> appStartedCompleter,
433 434 435
    String route,
    bool shouldBuild: true
  });
436

437 438 439 440 441
  bool get supportsRestart => false;

  Future<OperationResult> restart({ bool fullRestart: false, bool pauseAfterRestart: false }) {
    throw 'unsupported';
  }
442

443
  Future<Null> stop() async {
444
    _stopped = true;
445
    await stopEchoingDeviceLog();
446
    await preStop();
447 448 449
    return stopApp();
  }

450 451 452 453 454 455
  Future<Null> detach() async {
    await stopEchoingDeviceLog();
    await preStop();
    appFinished();
  }

456
  Future<Null> refreshViews() async {
457 458
    for (FlutterDevice device in flutterDevices)
      await device.refreshViews();
459 460
  }

461
  Future<Null> _debugDumpApp() async {
462
    await refreshViews();
463 464
    for (FlutterDevice device in flutterDevices)
      await device.debugDumpApp();
465 466
  }

467
  Future<Null> _debugDumpRenderTree() async {
468
    await refreshViews();
469 470
    for (FlutterDevice device in flutterDevices)
      await device.debugDumpRenderTree();
471 472
  }

473 474 475 476 477 478
  Future<Null> _debugDumpLayerTree() async {
    await refreshViews();
    for (FlutterDevice device in flutterDevices)
      await device.debugDumpLayerTree();
  }

479
  Future<Null> _debugDumpSemanticsTreeInTraversalOrder() async {
480 481
    await refreshViews();
    for (FlutterDevice device in flutterDevices)
482 483 484 485 486 487 488
      await device.debugDumpSemanticsTreeInTraversalOrder();
  }

  Future<Null> _debugDumpSemanticsTreeInInverseHitTestOrder() async {
    await refreshViews();
    for (FlutterDevice device in flutterDevices)
      await device.debugDumpSemanticsTreeInInverseHitTestOrder();
489 490
  }

491
  Future<Null> _debugToggleDebugPaintSizeEnabled() async {
492
    await refreshViews();
493 494
    for (FlutterDevice device in flutterDevices)
      await device.toggleDebugPaintSizeEnabled();
495 496
  }

497 498 499 500 501 502
  Future<Null> _debugTogglePerformanceOverlayOverride() async {
    await refreshViews();
    for (FlutterDevice device in flutterDevices)
      await device.debugTogglePerformanceOverlayOverride();
  }

503 504 505 506 507 508
  Future<Null> _debugToggleWidgetInspector() async {
    await refreshViews();
    for (FlutterDevice device in flutterDevices)
      await device.toggleWidgetInspector();
  }

509 510
  Future<Null> _screenshot(FlutterDevice device) async {
    final Status status = logger.startProgress('Taking screenshot for ${device.device.name}...');
511
    final File outputFile = getUniqueFile(fs.currentDirectory, 'flutter', 'png');
512
    try {
513
      if (supportsServiceProtocol && isRunningDebug) {
514
        await device.refreshViews();
515
        try {
516 517
          for (FlutterView view in device.views)
            await view.uiIsolate.flutterDebugAllowBanner(false);
518 519
        } catch (error) {
          status.stop();
520
          printError('Error communicating with Flutter on the device: $error');
521
        }
522 523
      }
      try {
524
        await device.device.takeScreenshot(outputFile);
525
      } finally {
526 527
        if (supportsServiceProtocol && isRunningDebug) {
          try {
528 529
            for (FlutterView view in device.views)
              await view.uiIsolate.flutterDebugAllowBanner(true);
530 531
          } catch (error) {
            status.stop();
532
            printError('Error communicating with Flutter on the device: $error');
533
          }
534 535
        }
      }
536
      final int sizeKB = (await outputFile.length()) ~/ 1024;
537
      status.stop();
538
      printStatus('Screenshot written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).');
539
    } catch (error) {
540
      status.stop();
541 542 543 544
      printError('Error taking screenshot: $error');
    }
  }

545
  Future<Null> _debugTogglePlatform() async {
546
    await refreshViews();
547 548 549 550 551
    final String from = await flutterDevices[0].views[0].uiIsolate.flutterPlatformOverride();
    String to;
    for (FlutterDevice device in flutterDevices)
      to = await device.togglePlatform(from: from);
    printStatus('Switched operating system to $to');
552 553
  }

554
  void registerSignalHandlers() {
555
    assert(stayResident);
556
    ProcessSignal.SIGINT.watch().listen(_cleanUpAndExit);
557
    ProcessSignal.SIGTERM.watch().listen(_cleanUpAndExit);
558
    if (!supportsServiceProtocol || !supportsRestart)
559
      return;
560 561
    ProcessSignal.SIGUSR1.watch().listen(_handleSignal);
    ProcessSignal.SIGUSR2.watch().listen(_handleSignal);
562 563
  }

564 565 566 567 568 569
  Future<Null> _cleanUpAndExit(ProcessSignal signal) async {
    _resetTerminal();
    await cleanupAfterSignal();
    exit(0);
  }

570
  bool _processingUserRequest = false;
571
  Future<Null> _handleSignal(ProcessSignal signal) async {
572
    if (_processingUserRequest) {
573 574 575
      printTrace('Ignoring signal: "$signal" because we are busy.');
      return;
    }
576
    _processingUserRequest = true;
577

578
    final bool fullRestart = signal == ProcessSignal.SIGUSR2;
579 580 581 582

    try {
      await restart(fullRestart: fullRestart);
    } finally {
583
      _processingUserRequest = false;
584
    }
585 586 587
  }

  Future<Null> stopEchoingDeviceLog() async {
588 589 590
    await Future.wait(
      flutterDevices.map((FlutterDevice device) => device.stopEchoingDeviceLog())
    );
591 592
  }

593 594 595 596
  /// If the [reloadSources] parameter is not null the 'reloadSources' service
  /// will be registered
  Future<Null> connectToServiceProtocol({String viewFilter,
      ReloadSources reloadSources}) async {
597
    if (!debuggingOptions.debuggingEnabled)
598
      return new Future<Null>.error('Error the service protocol is not enabled.');
599

600 601 602
    bool viewFound = false;
    for (FlutterDevice device in flutterDevices) {
      device.viewFilter = viewFilter;
603
      await device._connect(reloadSources: reloadSources);
604 605 606 607 608 609 610 611
      await device.getVMs();
      await device.waitForViews();
      if (device.views == null)
        printStatus('No Flutter views available on ${device.device.name}');
      else
        viewFound = true;
    }
    if (!viewFound)
612
      throwToolExit('No Flutter view is available');
613

614
    // Listen for service protocol connection to close.
615 616
    for (FlutterDevice device in flutterDevices) {
      for (VMService service in device.vmServices) {
617 618 619 620
        // This hooks up callbacks for when the connection stops in the future.
        // We don't want to wait for them. We don't handle errors in those callbacks'
        // futures either because they just print to logger and is not critical.
        service.done.then<Null>( // ignore: unawaited_futures
621 622 623 624
          _serviceProtocolDone,
          onError: _serviceProtocolError
        ).whenComplete(_serviceDisconnected);
      }
625
    }
626 627 628 629 630 631 632 633 634 635
  }

  Future<Null> _serviceProtocolDone(dynamic object) {
    printTrace('Service protocol connection closed.');
    return new Future<Null>.value(object);
  }

  Future<Null> _serviceProtocolError(dynamic error, StackTrace stack) {
    printTrace('Service protocol connection closed with an error: $error\n$stack');
    return new Future<Null>.error(error, stack);
636 637 638
  }

  /// Returns [true] if the input has been handled by this function.
639
  Future<bool> _commonTerminalInputHandler(String character) async {
640 641 642 643
    final String lower = character.toLowerCase();

    printStatus(''); // the key the user tapped might be on this line

644 645
    if (lower == 'h' || lower == '?') {
      // help
646
      printHelp(details: true);
647 648
      return true;
    } else if (lower == 'w') {
649 650
      if (supportsServiceProtocol) {
        await _debugDumpApp();
651
        return true;
652
      }
653
    } else if (lower == 't') {
654 655
      if (supportsServiceProtocol) {
        await _debugDumpRenderTree();
656
        return true;
657
      }
658 659 660 661 662 663 664
    } else if (character == 'L') {
      if (supportsServiceProtocol) {
        await _debugDumpLayerTree();
        return true;
      }
    } else if (character == 'S') {
      if (supportsServiceProtocol) {
665 666 667
        await _debugDumpSemanticsTreeInTraversalOrder();
        return true;
      }
668
    } else if (character == 'U') {
669 670
      if (supportsServiceProtocol) {
        await _debugDumpSemanticsTreeInInverseHitTestOrder();
671 672
        return true;
      }
673
    } else if (character == 'p') {
674 675
      if (supportsServiceProtocol && isRunningDebug) {
        await _debugToggleDebugPaintSizeEnabled();
676
        return true;
677
      }
678 679 680
    } else if (character == 'P') {
      if (supportsServiceProtocol) {
        await _debugTogglePerformanceOverlayOverride();
681 682 683 684
      }
    } else if (lower == 'i') {
      if (supportsServiceProtocol) {
        await _debugToggleWidgetInspector();
685 686
        return true;
      }
687
    } else if (character == 's') {
688 689 690
      for (FlutterDevice device in flutterDevices) {
        if (device.device.supportsScreenshot)
          await _screenshot(device);
691
      }
692
      return true;
693 694
    } else if (lower == 'o') {
      if (supportsServiceProtocol && isRunningDebug) {
695
        await _debugTogglePlatform();
696 697
        return true;
      }
698 699
    } else if (lower == 'q') {
      // exit
700
      await stop();
701
      return true;
702 703 704
    } else if (lower == 'd') {
      await detach();
      return true;
705 706 707 708 709
    }

    return false;
  }

710
  Future<Null> processTerminalInput(String command) async {
711 712
    // When terminal doesn't support line mode, '\n' can sneak into the input.
    command = command.trim();
713
    if (_processingUserRequest) {
714 715 716
      printTrace('Ignoring terminal input: "$command" because we are busy.');
      return;
    }
717
    _processingUserRequest = true;
718
    try {
719
      final bool handled = await _commonTerminalInputHandler(command);
720 721
      if (!handled)
        await handleTerminalCommand(command);
722 723 724
    } catch (error, st) {
      printError('$error\n$st');
      _cleanUpAndExit(null);
725
    } finally {
726
      _processingUserRequest = false;
727
    }
728 729
  }

730 731 732 733 734 735 736 737 738 739 740 741
  void _serviceDisconnected() {
    if (_stopped) {
      // User requested the application exit.
      return;
    }
    if (_finished.isCompleted)
      return;
    printStatus('Lost connection to device.');
    _resetTerminal();
    _finished.complete(0);
  }

742 743 744 745 746 747 748 749 750 751 752 753 754 755
  void appFinished() {
    if (_finished.isCompleted)
      return;
    printStatus('Application finished.');
    _resetTerminal();
    _finished.complete(0);
  }

  void _resetTerminal() {
    if (usesTerminalUI)
      terminal.singleCharMode = false;
  }

  void setupTerminal() {
756
    assert(stayResident);
757
    if (usesTerminalUI) {
758 759
      if (!logger.quiet) {
        printStatus('');
760
        printHelp(details: false);
761
      }
762
      terminal.singleCharMode = true;
763
      terminal.onCharInput.listen(processTerminalInput);
764 765 766 767
    }
  }

  Future<int> waitForAppToFinish() async {
768
    final int exitCode = await _finished.future;
769 770 771 772
    await cleanupAtFinish();
    return exitCode;
  }

773
  bool hasDirtyDependencies(FlutterDevice device) {
774
    final DartDependencySetBuilder dartDependencySetBuilder =
775
        new DartDependencySetBuilder(mainPath, packagesFilePath);
776
    final DependencyChecker dependencyChecker =
777
        new DependencyChecker(dartDependencySetBuilder, assetBundle);
778
    final String path = device.package.packagePath;
779
    if (path == null)
780 781
      return true;
    final FileStat stat = fs.file(path).statSync();
782
    if (stat.type != FileSystemEntityType.FILE)
783
      return true;
784
    if (!fs.file(path).existsSync())
785 786 787 788 789
      return true;
    final DateTime lastBuildTime = stat.modified;
    return dependencyChecker.check(lastBuildTime);
  }

790 791 792
  Future<Null> preStop() async { }

  Future<Null> stopApp() async {
793 794
    for (FlutterDevice device in flutterDevices)
      await device.stopApps();
795 796 797
    appFinished();
  }

798 799 800 801
  /// Called to print help to the terminal.
  void printHelp({ @required bool details });

  void printHelpDetails() {
802
    if (supportsServiceProtocol) {
803
      printStatus('You can dump the widget hierarchy of the app (debugDumpApp) by pressing "w".');
804
      printStatus('To dump the rendering tree of the app (debugDumpRenderTree), press "t".');
805
      if (isRunningDebug) {
806
        printStatus('For layers (debugDumpLayerTree), use "L"; accessibility (debugDumpSemantics), "S" (traversal order) or "U" (inverse hit test order).');
807
        printStatus('To toggle the widget inspector (WidgetsApp.showWidgetInspectorOverride), press "i".');
808 809
        printStatus('To toggle the display of construction lines (debugPaintSizeEnabled), press "p".');
        printStatus('To simulate different operating systems, (defaultTargetPlatform), press "o".');
810
      } else {
811
        printStatus('To dump the accessibility tree (debugDumpSemantics), press "S" (for traversal order) or "U" (for inverse hit test order).');
812
      }
813
      printStatus('To display the performance overlay (WidgetsApp.showPerformanceOverlay), press "P".');
814
    }
815
    if (flutterDevices.any((FlutterDevice d) => d.device.supportsScreenshot))
816
      printStatus('To save a screenshot to flutter.png, press "s".');
817 818
  }

819 820 821 822 823
  /// Called when a signal has requested we exit.
  Future<Null> cleanupAfterSignal();
  /// Called right before we exit.
  Future<Null> cleanupAtFinish();
  /// Called when the runner should handle a terminal command.
824
  Future<Null> handleTerminalCommand(String code);
825 826
}

Devon Carew's avatar
Devon Carew committed
827
class OperationResult {
828
  OperationResult(this.code, this.message, { this.hint });
Devon Carew's avatar
Devon Carew committed
829 830 831

  final int code;
  final String message;
832
  final String hint;
Devon Carew's avatar
Devon Carew committed
833 834

  bool get isOk => code == 0;
835 836

  static final OperationResult ok = new OperationResult(0, '');
Devon Carew's avatar
Devon Carew committed
837 838
}

839 840 841
/// Given the value of the --target option, return the path of the Dart file
/// where the app's main function should be.
String findMainDartFile([String target]) {
842
  target ??= '';
843
  final String targetPath = fs.path.absolute(target);
844
  if (fs.isDirectorySync(targetPath))
845
    return fs.path.join(targetPath, 'lib', 'main.dart');
846 847 848 849 850 851 852 853
  else
    return targetPath;
}

String getMissingPackageHintForPlatform(TargetPlatform platform) {
  switch (platform) {
    case TargetPlatform.android_arm:
    case TargetPlatform.android_x64:
854 855 856 857 858 859
    case TargetPlatform.android_x86:
      String manifest = 'android/AndroidManifest.xml';
      if (isProjectUsingGradle()) {
        manifest = gradleManifestPath;
      }
      return 'Is your project missing an $manifest?\nConsider running "flutter create ." to create one.';
860 861 862 863 864 865
    case TargetPlatform.ios:
      return 'Is your project missing an ios/Runner/Info.plist?\nConsider running "flutter create ." to create one.';
    default:
      return null;
  }
}
866 867

class DebugConnectionInfo {
868
  DebugConnectionInfo({ this.httpUri, this.wsUri, this.baseUri });
869

870 871 872 873
  // TODO(danrubel): the httpUri field should be removed as part of
  // https://github.com/flutter/flutter/issues/7050
  final Uri httpUri;
  final Uri wsUri;
874 875
  final String baseUri;
}