resident_web_runner.dart 25.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// 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:dwds/dwds.dart';
8
import 'package:meta/meta.dart';
9
import 'package:package_config/package_config.dart';
10
import 'package:vm_service/vm_service.dart' as vmservice;
11 12
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
    hide StackTrace;
13

14
import '../application_package.dart';
15
import '../base/async_guard.dart';
16
import '../base/common.dart';
17
import '../base/file_system.dart';
18
import '../base/io.dart';
19
import '../base/logger.dart';
20
import '../base/net.dart';
21 22 23
import '../base/terminal.dart';
import '../base/utils.dart';
import '../build_info.dart';
24
import '../cache.dart';
25
import '../convert.dart';
26
import '../dart/language_version.dart';
27
import '../dart/pub.dart';
28
import '../devfs.dart';
29
import '../device.dart';
30
import '../features.dart';
31
import '../globals.dart' as globals;
Dan Field's avatar
Dan Field committed
32 33
import '../platform_plugins.dart';
import '../plugins.dart';
34
import '../project.dart';
35
import '../reporting/reporting.dart';
36
import '../resident_runner.dart';
37
import '../run_hot.dart';
38
import '../vmservice.dart';
39
import '../web/chrome.dart';
40
import '../web/compile.dart';
41
import '../web/web_device.dart';
42
import '../web/web_runner.dart';
43
import 'devfs_web.dart';
44 45 46 47 48

/// Injectable factory to create a [ResidentWebRunner].
class DwdsWebRunnerFactory extends WebRunnerFactory {
  @override
  ResidentRunner createWebRunner(
49
    FlutterDevice device, {
50
    String target,
51
    @required bool stayResident,
52 53
    @required FlutterProject flutterProject,
    @required bool ipv6,
54
    @required DebuggingOptions debuggingOptions,
55
    @required UrlTunneller urlTunneller,
56
  }) {
57
    return _ResidentWebRunner(
58 59 60 61 62
      device,
      target: target,
      flutterProject: flutterProject,
      debuggingOptions: debuggingOptions,
      ipv6: ipv6,
63
      stayResident: stayResident,
64
      urlTunneller: urlTunneller,
65 66 67
    );
  }
}
68

69
const String kExitMessage = 'Failed to establish connection with the application '
70 71 72
  'instance in Chrome.\nThis can happen if the websocket connection used by the '
  'web tooling is unable to correctly establish a connection, for example due to a firewall.';

73
/// A hot-runner which handles browser specific delegation.
74 75
abstract class ResidentWebRunner extends ResidentRunner {
  ResidentWebRunner(
76
    FlutterDevice device, {
77 78 79
    String target,
    @required this.flutterProject,
    @required bool ipv6,
80
    @required DebuggingOptions debuggingOptions,
81
    bool stayResident = true,
82
  }) : super(
83
          <FlutterDevice>[device],
84
          target: target ?? globals.fs.path.join('lib', 'main.dart'),
85
          debuggingOptions: debuggingOptions,
86
          ipv6: ipv6,
87
          stayResident: stayResident,
88 89
        );

90
  FlutterDevice get device => flutterDevices.first;
91
  final FlutterProject flutterProject;
92
  DateTime firstBuildTime;
93

Dan Field's avatar
Dan Field committed
94 95 96 97
  // Used with the new compiler to generate a bootstrap file containing plugins
  // and platform initialization.
  Directory _generatedEntrypointDirectory;

98 99
  // Only the debug builds of the web support the service protocol.
  @override
100
  bool get supportsServiceProtocol => isRunningDebug && deviceIsDebuggable;
101 102

  @override
103 104 105 106 107
  bool get debuggingEnabled => isRunningDebug && deviceIsDebuggable;

  /// WebServer device is debuggable when running with --start-paused.
  bool get deviceIsDebuggable => device.device is! WebServerDevice || debuggingOptions.startPaused;

108 109 110
  @override
  bool get supportsWriteSkSL => false;

111
  bool get _enableDwds => debuggingEnabled;
112

113
  ConnectionResult _connectionResult;
114
  StreamSubscription<vmservice.Event> _stdOutSub;
115
  StreamSubscription<vmservice.Event> _stdErrSub;
116
  StreamSubscription<vmservice.Event> _extensionEventSub;
117
  bool _exited = false;
118
  WipConnection _wipConnection;
119
  ChromiumLauncher _chromiumLauncher;
120

121 122
  vmservice.VmService get _vmService =>
      _connectionResult?.debugConnection?.vmService;
123

124
  @override
125 126 127
  bool get canHotRestart {
    return true;
  }
128

129
  @override
130 131 132 133
  Future<Map<String, dynamic>> invokeFlutterExtensionRpcRawOnFirstIsolate(
    String method, {
    Map<String, dynamic> params,
  }) async {
134 135
    final vmservice.Response response =
        await _vmService.callServiceExtension(method, args: params);
136
    return response.toJson();
137 138 139
  }

  @override
140
  Future<void> cleanupAfterSignal() async {
141
    await _cleanup();
142 143 144
  }

  @override
145
  Future<void> cleanupAtFinish() async {
146 147 148 149
    await _cleanup();
  }

  Future<void> _cleanup() async {
150 151 152
    if (_exited) {
      return;
    }
153
    await _stdOutSub?.cancel();
154
    await _stdErrSub?.cancel();
155
    await _extensionEventSub?.cancel();
156
    await device.device.stopApp(null);
157 158 159 160 161 162 163 164
    try {
      _generatedEntrypointDirectory?.deleteSync(recursive: true);
    } on FileSystemException {
      // Best effort to clean up temp dirs.
      globals.printTrace(
        'Failed to clean up temp directory: ${_generatedEntrypointDirectory.path}',
      );
    }
165
    _exited = true;
166 167
  }

168 169 170 171 172
  Future<void> _cleanupAndExit() async {
    await _cleanup();
    appFinished();
  }

173
  @override
174 175 176 177
  void printHelp({bool details = true}) {
    if (details) {
      return printHelpDetails();
    }
178
    const String fire = '🔥';
179
    const String rawMessage =
180
        '  To hot restart changes while running, press "r" or "R".';
181 182
    final String message = globals.terminal.color(
      fire + globals.terminal.bolden(rawMessage),
183 184
      TerminalColor.red,
    );
185
    globals.printStatus(
186
        "Warning: Flutter's support for web development is not stable yet and hasn't");
187 188 189 190
    globals.printStatus('been thoroughly tested in production environments.');
    globals.printStatus('For more information see https://flutter.dev/web');
    globals.printStatus('');
    globals.printStatus(message);
191
    const String quitMessage = 'To quit, press "q".';
192
    globals.printStatus('For a more detailed help message, press "h". $quitMessage');
193 194
  }

195 196 197 198 199
  @override
  Future<List<FlutterView>> listFlutterViews() async {
    return <FlutterView>[];
  }

200 201 202
  @override
  Future<void> debugDumpApp() async {
    try {
203 204 205 206
      await _vmService
        ?.flutterDebugDumpApp(
          isolateId: null,
        );
207 208 209 210 211 212 213 214
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugDumpRenderTree() async {
    try {
215 216 217 218
      await _vmService
        ?.flutterDebugDumpRenderTree(
          isolateId: null,
        );
219 220 221 222 223 224 225 226
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugDumpLayerTree() async {
    try {
227 228 229 230
      await _vmService
        ?.flutterDebugDumpLayerTree(
          isolateId: null,
        );
231 232 233 234 235 236 237 238
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugDumpSemanticsTreeInTraversalOrder() async {
    try {
239 240 241 242
      await _vmService
        ?.flutterDebugDumpSemanticsTreeInTraversalOrder(
          isolateId: null,
        );
243 244 245 246 247 248 249 250
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugTogglePlatform() async {
    try {
251 252 253 254
      final String currentPlatform = await _vmService
        ?.flutterPlatformOverride(
          isolateId: null,
        );
255
      final String platform = nextPlatform(currentPlatform, featureFlags);
256 257 258 259 260
      await _vmService
        ?.flutterPlatformOverride(
            platform: platform,
            isolateId: null,
          );
261
      globals.printStatus('Switched operating system to $platform');
262 263 264 265 266
    } on vmservice.RPCError {
      return;
    }
  }

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  @override
  Future<void> debugToggleBrightness() async {
    try {
      final Brightness currentBrightness = await _vmService
        ?.flutterBrightnessOverride(
          isolateId: null,
        );
      Brightness next;
      if (currentBrightness == Brightness.light) {
        next = Brightness.dark;
      } else if (currentBrightness == Brightness.dark) {
        next = Brightness.light;
      }
      next = await _vmService
        ?.flutterBrightnessOverride(
            brightness: next,
            isolateId: null,
          );
      globals.logger.printStatus('Changed brightness to $next.');
    } on vmservice.RPCError {
      return;
    }
  }

291 292 293 294 295 296
  @override
  Future<void> stopEchoingDeviceLog() async {
    // Do nothing for ResidentWebRunner
    await device.stopEchoingDeviceLog();
  }

297 298 299
  @override
  Future<void> debugDumpSemanticsTreeInInverseHitTestOrder() async {
    try {
300 301 302 303
      await _vmService
        ?.flutterDebugDumpSemanticsTreeInInverseHitTestOrder(
          isolateId: null,
        );
304 305 306 307 308 309 310 311
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleDebugPaintSizeEnabled() async {
    try {
312 313 314 315
      await _vmService
        ?.flutterToggleDebugPaintSizeEnabled(
          isolateId: null,
        );
316 317 318 319 320 321 322 323
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleDebugCheckElevationsEnabled() async {
    try {
324 325 326 327
      await _vmService
        ?.flutterToggleDebugCheckElevationsEnabled(
          isolateId: null,
        );
328 329 330 331 332 333 334 335
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugTogglePerformanceOverlayOverride() async {
    try {
336 337 338 339
      await _vmService
        ?.flutterTogglePerformanceOverlayOverride(
          isolateId: null,
        );
340 341 342 343 344 345 346 347
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleWidgetInspector() async {
    try {
348 349 350 351
      await _vmService
        ?.flutterToggleWidgetInspector(
          isolateId: null,
        );
352 353 354 355 356 357 358 359
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleProfileWidgetBuilds() async {
    try {
360 361 362 363
      await _vmService
        ?.flutterToggleProfileWidgetBuilds(
          isolateId: null,
        );
364 365 366 367 368 369
    } on vmservice.RPCError {
      return;
    }
  }
}

370 371
class _ResidentWebRunner extends ResidentWebRunner {
  _ResidentWebRunner(
372 373 374 375 376 377
    FlutterDevice device, {
    String target,
    @required FlutterProject flutterProject,
    @required bool ipv6,
    @required DebuggingOptions debuggingOptions,
    bool stayResident = true,
378
    @required this.urlTunneller,
379 380 381
  }) : super(
          device,
          flutterProject: flutterProject,
382
          target: target ?? globals.fs.path.join('lib', 'main.dart'),
383 384 385 386 387
          debuggingOptions: debuggingOptions,
          ipv6: ipv6,
          stayResident: stayResident,
        );

388
  final UrlTunneller urlTunneller;
389

390 391 392 393 394 395
  @override
  Future<int> run({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
    String route,
  }) async {
396
    firstBuildTime = DateTime.now();
397 398
    final ApplicationPackage package = await ApplicationPackageFactory.instance.getPackageForPlatform(
      TargetPlatform.web_javascript,
399
      buildInfo: debuggingOptions.buildInfo,
400 401 402
      applicationBinary: null,
    );
    if (package == null) {
403 404
      globals.printStatus('This application is not configured to build on the web.');
      globals.printStatus('To add web support to a project, run `flutter create .`.');
405
    }
406
    if (!globals.fs.isFileSync(mainPath)) {
407 408 409 410 411
      String message = 'Tried to run $mainPath, but that file does not exist.';
      if (target == null) {
        message +=
            '\nConsider using the -t option to specify the Dart file to start.';
      }
412
      globals.printError(message);
413 414
      return 1;
    }
415
    final String modeName = debuggingOptions.buildInfo.friendlyModeName;
416
    globals.printStatus(
417
      'Launching ${globals.fsUtils.getDisplayPath(target)} '
418 419
      'on ${device.device.name} in $modeName mode...',
    );
420 421
    final String effectiveHostname = debuggingOptions.hostname ?? 'localhost';
    final int hostPort = debuggingOptions.port == null
422
        ? await globals.os.findFreePort()
423
        : int.tryParse(debuggingOptions.port);
424

425 426 427 428
    if (device.device is ChromiumDevice) {
      _chromiumLauncher = (device.device as ChromiumDevice).chromeLauncher;
    }

429 430
    try {
      return await asyncGuard(() async {
431 432 433 434 435 436 437 438
        // Ensure dwds resources are cached. If the .packages file is missing then
        // the client.js script cannot be located by the injected handler in dwds.
        // This will result in a NoSuchMethodError thrown by injected_handler.darts
        await pub.get(
          context: PubContext.pubGet,
          directory: globals.fs.path.join(Cache.flutterRoot, 'packages', 'flutter_tools')
        );

439 440 441 442 443
        final ExpressionCompiler expressionCompiler =
          debuggingOptions.webEnableExpressionEvaluation
              ? WebExpressionCompiler(device.generator)
              : null;

444 445 446 447 448
        device.devFS = WebDevFS(
          hostname: effectiveHostname,
          port: hostPort,
          packagesFilePath: packagesFilePath,
          urlTunneller: urlTunneller,
449
          useSseForDebugProxy: debuggingOptions.webUseSseForDebugProxy,
450
          buildInfo: debuggingOptions.buildInfo,
451 452
          enableDwds: _enableDwds,
          entrypoint: globals.fs.file(target).uri,
453
          expressionCompiler: expressionCompiler,
454
          chromiumLauncher: _chromiumLauncher,
455 456 457 458 459 460 461 462 463
        );
        final Uri url = await device.devFS.create();
        if (debuggingOptions.buildInfo.isDebug) {
          final UpdateFSReport report = await _updateDevFS(fullRestart: true);
          if (!report.success) {
            globals.printError('Failed to compile application.');
            return 1;
          }
          device.generator.accept();
464
          cacheInitialDillCompilation();
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        } else {
          await buildWeb(
            flutterProject,
            target,
            debuggingOptions.buildInfo,
            debuggingOptions.initializePlatform,
            false,
          );
        }
        await device.device.startApp(
          package,
          mainPath: target,
          debuggingOptions: debuggingOptions,
          platformArgs: <String, Object>{
            'uri': url.toString(),
          },
        );
        return attach(
          connectionInfoCompleter: connectionInfoCompleter,
          appStartedCompleter: appStartedCompleter,
        );
      });
    } on WebSocketException {
      throwToolExit(kExitMessage);
    } on ChromeDebugException {
      throwToolExit(kExitMessage);
    } on AppConnectionException {
      throwToolExit(kExitMessage);
    } on SocketException {
      throwToolExit(kExitMessage);
495
    }
496
    return 0;
497 498 499 500 501
  }

  @override
  Future<OperationResult> restart({
    bool fullRestart = false,
502
    bool pause = false,
503 504 505 506
    String reason,
    bool benchmarkMode = false,
  }) async {
    final Stopwatch timer = Stopwatch()..start();
507
    final Status status = globals.logger.startProgress(
508 509 510 511 512 513 514
      'Performing hot restart...',
      timeout: supportsServiceProtocol
          ? timeoutConfiguration.fastOperation
          : timeoutConfiguration.slowOperation,
      progressId: 'hot.restart',
    );

515
    if (debuggingOptions.buildInfo.isDebug) {
516
      await runSourceGenerators();
517 518 519 520 521 522 523 524 525
      // Full restart is always false for web, since the extra recompile is wasteful.
      final UpdateFSReport report = await _updateDevFS(fullRestart: false);
      if (report.success) {
        device.generator.accept();
      } else {
        status.stop();
        await device.generator.reject();
        return OperationResult(1, 'Failed to recompile application.');
      }
526
    } else {
527 528 529 530 531 532 533 534 535 536 537
      try {
        await buildWeb(
          flutterProject,
          target,
          debuggingOptions.buildInfo,
          debuggingOptions.initializePlatform,
          false,
        );
      } on ToolExit {
        return OperationResult(1, 'Failed to recompile application.');
      }
538 539 540
    }

    try {
541 542
      if (!deviceIsDebuggable) {
        globals.printStatus('Recompile complete. Page requires refresh.');
543 544 545
      } else if (isRunningDebug) {
        await _vmService.callMethod('hotRestart');
      } else {
546 547 548 549 550
        // On non-debug builds, a hard refresh is required to ensure the
        // up to date sources are loaded.
        await _wipConnection?.sendCommand('Page.reload', <String, Object>{
          'ignoreCache': !debuggingOptions.buildInfo.isDebug,
        });
551
      }
552 553
    } on Exception catch (err) {
      return OperationResult(1, err.toString(), fatal: true);
554 555 556
    } finally {
      status.stop();
    }
557

558 559
    final String elapsed = getElapsedAsMilliseconds(timer.elapsed);
    globals.printStatus('Restarted application in $elapsed.');
560 561 562

    // Don't track restart times for dart2js builds or web-server devices.
    if (debuggingOptions.buildInfo.isDebug && deviceIsDebuggable) {
563
      globals.flutterUsage.sendTiming('hot', 'web-incremental-restart', timer.elapsed);
564 565 566 567 568 569 570 571
      HotEvent(
        'restart',
        targetPlatform: getNameForTargetPlatform(TargetPlatform.web_javascript),
        sdkName: await device.device.sdkNameAndVersion,
        emulator: false,
        fullRestart: true,
        reason: reason,
        overallTimeInMs: timer.elapsed.inMilliseconds,
572
        nullSafety: usageNullSafety,
573
      ).send();
574 575 576 577
    }
    return OperationResult.ok;
  }

Dan Field's avatar
Dan Field committed
578 579 580
  // Flutter web projects need to include a generated main entrypoint to call the
  // appropriate bootstrap method and inject plugins.
  // Keep this in sync with build_system/targets/web.dart.
581
  Future<Uri> _generateEntrypoint(Uri mainUri, PackageConfig packageConfig) async {
Dan Field's avatar
Dan Field committed
582 583 584 585 586 587
    File result = _generatedEntrypointDirectory?.childFile('web_entrypoint.dart');
    if (_generatedEntrypointDirectory == null) {
      _generatedEntrypointDirectory ??= globals.fs.systemTempDirectory.createTempSync('flutter_tools.')
        ..createSync();
      result = _generatedEntrypointDirectory.childFile('web_entrypoint.dart');

588
      final bool hasWebPlugins = (await findPlugins(flutterProject))
Dan Field's avatar
Dan Field committed
589 590 591
        .any((Plugin p) => p.platforms.containsKey(WebPlugin.kConfigKey));
      await injectPlugins(flutterProject, checkProjects: true);

592
      final Uri generatedUri = globals.fs.currentDirectory
Dan Field's avatar
Dan Field committed
593 594
        .childDirectory('lib')
        .childFile('generated_plugin_registrant.dart')
595 596 597
        .absolute.uri;
      final Uri generatedImport = packageConfig.toPackageUri(generatedUri);
      Uri importedEntrypoint = packageConfig.toPackageUri(mainUri);
598 599
      // Special handling for entrypoints that are not under lib, such as test scripts.
      if (importedEntrypoint == null) {
600
        final String parent = globals.fs.file(mainUri).parent.path;
601
        flutterDevices.first.generator.addFileSystemRoot(parent);
602
        flutterDevices.first.generator.addFileSystemRoot(globals.fs.directory('test').absolute.path);
603 604 605 606
        importedEntrypoint = Uri(
          scheme: 'org-dartlang-app',
          path: '/' + mainUri.pathSegments.last,
        );
607
      }
Dan Field's avatar
Dan Field committed
608 609

      final String entrypoint = <String>[
610 611 612 613
        determineLanguageVersion(
          globals.fs.file(mainUri),
          packageConfig[flutterProject.manifest.appName],
        ),
614 615 616 617 618
        '// Flutter web bootstrap script for $importedEntrypoint.',
        '',
        "import 'dart:ui' as ui;",
        '',
        "import '$importedEntrypoint' as entrypoint;",
Dan Field's avatar
Dan Field committed
619
        if (hasWebPlugins)
620
          "import 'package:flutter_web_plugins/flutter_web_plugins.dart';",
Dan Field's avatar
Dan Field committed
621
        if (hasWebPlugins)
622 623
          "import '$generatedImport';",
        '',
Dan Field's avatar
Dan Field committed
624 625
        'Future<void> main() async {',
        if (hasWebPlugins)
626
          '  registerPlugins(webPluginRegistry);',
Dan Field's avatar
Dan Field committed
627 628 629
        '  await ui.webOnlyInitializePlatform();',
        '  entrypoint.main();',
        '}',
630
        '',
Dan Field's avatar
Dan Field committed
631 632 633
      ].join('\n');
      result.writeAsStringSync(entrypoint);
    }
634
    return result.absolute.uri;
Dan Field's avatar
Dan Field committed
635 636
  }

637 638 639 640
  Future<UpdateFSReport> _updateDevFS({bool fullRestart = false}) async {
    final bool isFirstUpload = !assetBundle.wasBuiltOnce();
    final bool rebuildBundle = assetBundle.needsBuild();
    if (rebuildBundle) {
641
      globals.printTrace('Updating assets');
642
      final int result = await assetBundle.build(packagesPath: debuggingOptions.buildInfo.packagesPath);
643 644 645 646
      if (result != 0) {
        return UpdateFSReport(success: false);
      }
    }
647
    final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated(
648 649 650
      lastCompiled: device.devFS.lastCompiled,
      urisToMonitor: device.devFS.sources,
      packagesPath: packagesFilePath,
651
      packageConfig: device.devFS.lastPackageConfig,
652
    );
653
    final Status devFSStatus = globals.logger.startProgress(
654 655 656 657
      'Syncing files to device ${device.device.name}...',
      timeout: timeoutConfiguration.fastOperation,
    );
    final UpdateFSReport report = await device.devFS.update(
658 659 660 661
      mainUri: await _generateEntrypoint(
        globals.fs.file(mainPath).absolute.uri,
        invalidationResult.packageConfig,
      ),
662 663 664 665 666 667 668 669 670
      target: target,
      bundle: assetBundle,
      firstBuildTime: firstBuildTime,
      bundleFirstUpload: isFirstUpload,
      generator: device.generator,
      fullRestart: fullRestart,
      dillOutputPath: dillOutputPath,
      projectRootPath: projectRootPath,
      pathToReload: getReloadPath(fullRestart: fullRestart),
671 672
      invalidatedFiles: invalidationResult.uris,
      packageConfig: invalidationResult.packageConfig,
673
      trackWidgetCreation: debuggingOptions.buildInfo.trackWidgetCreation,
674 675
    );
    devFSStatus.stop();
676
    globals.printTrace('Synced ${getSizeAsMB(report.syncedBytes)}.');
677 678 679 680 681 682 683 684
    return report;
  }

  @override
  Future<int> attach({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
  }) async {
685 686
    if (_chromiumLauncher != null) {
      final Chromium chrome = await _chromiumLauncher.connectedInstance;
687
      final ChromeTab chromeTab = await chrome.chromeConnection.getTab((ChromeTab chromeTab) {
688
        return !chromeTab.url.startsWith('chrome-extension');
689
      });
690 691 692
      if (chromeTab == null) {
        throwToolExit('Failed to connect to Chrome instance.');
      }
693 694
      _wipConnection = await chromeTab.connect();
    }
695 696
    Uri websocketUri;
    if (supportsServiceProtocol) {
697 698 699 700 701
      final WebDevFS webDevFS = device.devFS as WebDevFS;
      final bool useDebugExtension = device.device is WebServerDevice && debuggingOptions.startPaused;
      _connectionResult = await webDevFS.connect(useDebugExtension);
      unawaited(_connectionResult.debugConnection.onDone.whenComplete(_cleanupAndExit));

702 703 704 705 706 707 708 709
      _stdOutSub = _vmService.onStdoutEvent.listen((vmservice.Event log) {
        final String message = utf8.decode(base64.decode(log.bytes));
        globals.printStatus(message, newline: false);
      });
      _stdErrSub = _vmService.onStderrEvent.listen((vmservice.Event log) {
        final String message = utf8.decode(base64.decode(log.bytes));
        globals.printStatus(message, newline: false);
      });
710 711
      _extensionEventSub =
          _vmService.onExtensionEvent.listen(printStructuredErrorLog);
712
      try {
713
        await _vmService.streamListen(vmservice.EventStreams.kStdout);
714 715 716 717 718
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
      }
      try {
719
        await _vmService.streamListen(vmservice.EventStreams.kStderr);
720 721 722
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
723
      }
724
      try {
725
        await _vmService.streamListen(vmservice.EventStreams.kIsolate);
726 727 728
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
729
      }
730 731 732 733 734 735
      try {
        await _vmService.streamListen(vmservice.EventStreams.kExtension);
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
      }
736
      unawaited(_vmService.registerService('reloadSources', 'FlutterTools'));
737 738 739 740 741 742
      _vmService.registerServiceCallback('reloadSources', (Map<String, Object> params) async {
        final bool pause = params['pause'] as bool ?? false;
        await restart(benchmarkMode: false, pause: pause, fullRestart: false);
        return <String, Object>{'type': 'Success'};
      });

743 744 745 746 747 748 749 750 751 752 753 754
      websocketUri = Uri.parse(_connectionResult.debugConnection.uri);
      // Always run main after connecting because start paused doesn't work yet.
      if (!debuggingOptions.startPaused || !supportsServiceProtocol) {
        _connectionResult.appConnection.runMain();
      } else {
        StreamSubscription<void> resumeSub;
        resumeSub = _connectionResult.debugConnection.vmService.onDebugEvent
            .listen((vmservice.Event event) {
          if (event.type == vmservice.EventKind.kResume) {
            _connectionResult.appConnection.runMain();
            resumeSub.cancel();
          }
755
        });
756
      }
757
    }
758
    if (websocketUri != null) {
759 760 761 762 763
      if (debuggingOptions.vmserviceOutFile != null) {
        globals.fs.file(debuggingOptions.vmserviceOutFile)
          ..createSync(recursive: true)
          ..writeAsStringSync(websocketUri.toString());
      }
764
      globals.printStatus('Debug service listening on $websocketUri');
765
    }
766
    appStartedCompleter?.complete();
767 768 769 770 771 772
    connectionInfoCompleter?.complete(DebugConnectionInfo(wsUri: websocketUri));
    if (stayResident) {
      await waitForAppToFinish();
    } else {
      await stopEchoingDeviceLog();
      await exitApp();
773
    }
774 775
    await cleanupAtFinish();
    return 0;
776
  }
777

778 779 780 781
  @override
  bool get supportsCanvasKit => supportsServiceProtocol;

  @override
782
  Future<bool> toggleCanvaskit() async {
783 784 785
    final WebDevFS webDevFS = device.devFS as WebDevFS;
    webDevFS.webAssetServer.canvasKitRendering = !webDevFS.webAssetServer.canvasKitRendering;
    await _wipConnection?.sendCommand('Page.reload');
786
    return webDevFS.webAssetServer.canvasKitRendering;
787 788
  }

789 790 791 792 793
  @override
  Future<void> exitApp() async {
    await device.exitApps();
    appFinished();
  }
794
}