resident_web_runner.dart 26.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 '../build_system/targets/web.dart';
25
import '../cache.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
    bool machine = false,
57
  }) {
58
    return _ResidentWebRunner(
59 60 61 62 63
      device,
      target: target,
      flutterProject: flutterProject,
      debuggingOptions: debuggingOptions,
      ipv6: ipv6,
64
      stayResident: stayResident,
65
      urlTunneller: urlTunneller,
66
      machine: machine,
67 68 69
    );
  }
}
70

71
const String kExitMessage = 'Failed to establish connection with the application '
72 73 74
  '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.';

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

94
  FlutterDevice get device => flutterDevices.first;
95
  final FlutterProject flutterProject;
96
  DateTime firstBuildTime;
97

Dan Field's avatar
Dan Field committed
98 99 100 101
  // Used with the new compiler to generate a bootstrap file containing plugins
  // and platform initialization.
  Directory _generatedEntrypointDirectory;

102 103
  // Only the debug builds of the web support the service protocol.
  @override
104
  bool get supportsServiceProtocol => isRunningDebug && deviceIsDebuggable;
105 106

  @override
107 108 109 110 111
  bool get debuggingEnabled => isRunningDebug && deviceIsDebuggable;

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

112 113 114
  @override
  bool get supportsWriteSkSL => false;

115
  bool get _enableDwds => debuggingEnabled;
116

117
  ConnectionResult _connectionResult;
118
  StreamSubscription<vmservice.Event> _stdOutSub;
119
  StreamSubscription<vmservice.Event> _stdErrSub;
120
  StreamSubscription<vmservice.Event> _extensionEventSub;
121
  bool _exited = false;
122
  WipConnection _wipConnection;
123
  ChromiumLauncher _chromiumLauncher;
124

125 126
  vmservice.VmService get _vmService =>
      _connectionResult?.debugConnection?.vmService;
127

128
  @override
129 130 131
  bool get canHotRestart {
    return true;
  }
132

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

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

  @override
149
  Future<void> cleanupAtFinish() async {
150 151 152 153
    await _cleanup();
  }

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

172 173 174 175 176
  Future<void> _cleanupAndExit() async {
    await _cleanup();
    appFinished();
  }

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

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

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

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

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

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

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  @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;
    }
  }

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

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

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

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

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

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

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

370 371 372
  @override
  Future<void> debugToggleProfileWidgetBuilds() async {
    try {
373 374 375 376
      await _vmService
        ?.flutterToggleProfileWidgetBuilds(
          isolateId: null,
        );
377 378 379 380 381 382
    } on vmservice.RPCError {
      return;
    }
  }
}

383 384
class _ResidentWebRunner extends ResidentWebRunner {
  _ResidentWebRunner(
385 386 387 388 389 390
    FlutterDevice device, {
    String target,
    @required FlutterProject flutterProject,
    @required bool ipv6,
    @required DebuggingOptions debuggingOptions,
    bool stayResident = true,
391
    @required this.urlTunneller,
392
    bool machine = false,
393 394 395
  }) : super(
          device,
          flutterProject: flutterProject,
396
          target: target ?? globals.fs.path.join('lib', 'main.dart'),
397 398 399
          debuggingOptions: debuggingOptions,
          ipv6: ipv6,
          stayResident: stayResident,
400
          machine: machine,
401 402
        );

403
  final UrlTunneller urlTunneller;
404

405 406 407 408 409 410
  @override
  Future<int> run({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
    String route,
  }) async {
411
    firstBuildTime = DateTime.now();
412 413
    final ApplicationPackage package = await ApplicationPackageFactory.instance.getPackageForPlatform(
      TargetPlatform.web_javascript,
414
      buildInfo: debuggingOptions.buildInfo,
415 416 417
      applicationBinary: null,
    );
    if (package == null) {
418 419
      globals.printStatus('This application is not configured to build on the web.');
      globals.printStatus('To add web support to a project, run `flutter create .`.');
420
    }
421
    if (!globals.fs.isFileSync(mainPath)) {
422 423 424 425 426
      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.';
      }
427
      globals.printError(message);
428
      appFailedToStart();
429 430
      return 1;
    }
431
    final String modeName = debuggingOptions.buildInfo.friendlyModeName;
432
    globals.printStatus(
433
      'Launching ${globals.fsUtils.getDisplayPath(target)} '
434 435
      'on ${device.device.name} in $modeName mode...',
    );
436 437
    final String effectiveHostname = debuggingOptions.hostname ?? 'localhost';
    final int hostPort = debuggingOptions.port == null
438
        ? await globals.os.findFreePort()
439
        : int.tryParse(debuggingOptions.port);
440

441 442 443 444
    if (device.device is ChromiumDevice) {
      _chromiumLauncher = (device.device as ChromiumDevice).chromeLauncher;
    }

445 446
    try {
      return await asyncGuard(() async {
447 448 449 450 451
        // 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,
452 453
          directory: globals.fs.path.join(Cache.flutterRoot, 'packages', 'flutter_tools'),
          generateSyntheticPackage: false,
454 455
        );

456 457 458 459 460
        final ExpressionCompiler expressionCompiler =
          debuggingOptions.webEnableExpressionEvaluation
              ? WebExpressionCompiler(device.generator)
              : null;

461 462 463 464 465
        device.devFS = WebDevFS(
          hostname: effectiveHostname,
          port: hostPort,
          packagesFilePath: packagesFilePath,
          urlTunneller: urlTunneller,
466
          useSseForDebugProxy: debuggingOptions.webUseSseForDebugProxy,
467
          useSseForDebugBackend: debuggingOptions.webUseSseForDebugBackend,
468
          buildInfo: debuggingOptions.buildInfo,
469 470
          enableDwds: _enableDwds,
          entrypoint: globals.fs.file(target).uri,
471
          expressionCompiler: expressionCompiler,
472
          chromiumLauncher: _chromiumLauncher,
473
          nullAssertions: debuggingOptions.nullAssertions,
474 475 476 477 478 479
        );
        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.');
480
            appFailedToStart();
481 482 483
            return 1;
          }
          device.generator.accept();
484
          cacheInitialDillCompilation();
485 486 487 488 489 490 491
        } else {
          await buildWeb(
            flutterProject,
            target,
            debuggingOptions.buildInfo,
            debuggingOptions.initializePlatform,
            false,
492
            kNoneWorker,
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
          );
        }
        await device.device.startApp(
          package,
          mainPath: target,
          debuggingOptions: debuggingOptions,
          platformArgs: <String, Object>{
            'uri': url.toString(),
          },
        );
        return attach(
          connectionInfoCompleter: connectionInfoCompleter,
          appStartedCompleter: appStartedCompleter,
        );
      });
    } on WebSocketException {
509
      appFailedToStart();
510 511
      throwToolExit(kExitMessage);
    } on ChromeDebugException {
512
      appFailedToStart();
513 514
      throwToolExit(kExitMessage);
    } on AppConnectionException {
515
      appFailedToStart();
516 517
      throwToolExit(kExitMessage);
    } on SocketException {
518
      appFailedToStart();
519
      throwToolExit(kExitMessage);
520 521 522
    } on Exception {
      appFailedToStart();
      rethrow;
523
    }
524
    return 0;
525 526 527 528 529
  }

  @override
  Future<OperationResult> restart({
    bool fullRestart = false,
530
    bool pause = false,
531 532 533 534
    String reason,
    bool benchmarkMode = false,
  }) async {
    final Stopwatch timer = Stopwatch()..start();
535
    final Status status = globals.logger.startProgress(
536 537 538 539 540 541 542
      'Performing hot restart...',
      timeout: supportsServiceProtocol
          ? timeoutConfiguration.fastOperation
          : timeoutConfiguration.slowOperation,
      progressId: 'hot.restart',
    );

543
    if (debuggingOptions.buildInfo.isDebug) {
544
      await runSourceGenerators();
545 546 547 548 549 550 551 552 553
      // 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.');
      }
554
    } else {
555 556 557 558 559 560 561
      try {
        await buildWeb(
          flutterProject,
          target,
          debuggingOptions.buildInfo,
          debuggingOptions.initializePlatform,
          false,
562
          kNoneWorker,
563 564 565 566
        );
      } on ToolExit {
        return OperationResult(1, 'Failed to recompile application.');
      }
567 568 569
    }

    try {
570 571
      if (!deviceIsDebuggable) {
        globals.printStatus('Recompile complete. Page requires refresh.');
572 573 574
      } else if (isRunningDebug) {
        await _vmService.callMethod('hotRestart');
      } else {
575 576 577 578 579
        // 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,
        });
580
      }
581 582
    } on Exception catch (err) {
      return OperationResult(1, err.toString(), fatal: true);
583 584 585
    } finally {
      status.stop();
    }
586

587 588
    final String elapsed = getElapsedAsMilliseconds(timer.elapsed);
    globals.printStatus('Restarted application in $elapsed.');
589 590 591

    // Don't track restart times for dart2js builds or web-server devices.
    if (debuggingOptions.buildInfo.isDebug && deviceIsDebuggable) {
592
      globals.flutterUsage.sendTiming('hot', 'web-incremental-restart', timer.elapsed);
593 594 595 596 597 598 599 600
      HotEvent(
        'restart',
        targetPlatform: getNameForTargetPlatform(TargetPlatform.web_javascript),
        sdkName: await device.device.sdkNameAndVersion,
        emulator: false,
        fullRestart: true,
        reason: reason,
        overallTimeInMs: timer.elapsed.inMilliseconds,
601
        nullSafety: usageNullSafety,
602
      ).send();
603 604 605 606
    }
    return OperationResult.ok;
  }

Dan Field's avatar
Dan Field committed
607 608 609
  // 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.
610
  Future<Uri> _generateEntrypoint(Uri mainUri, PackageConfig packageConfig) async {
Dan Field's avatar
Dan Field committed
611 612 613 614 615 616
    File result = _generatedEntrypointDirectory?.childFile('web_entrypoint.dart');
    if (_generatedEntrypointDirectory == null) {
      _generatedEntrypointDirectory ??= globals.fs.systemTempDirectory.createTempSync('flutter_tools.')
        ..createSync();
      result = _generatedEntrypointDirectory.childFile('web_entrypoint.dart');

617
      final bool hasWebPlugins = (await findPlugins(flutterProject))
Dan Field's avatar
Dan Field committed
618 619 620
        .any((Plugin p) => p.platforms.containsKey(WebPlugin.kConfigKey));
      await injectPlugins(flutterProject, checkProjects: true);

621
      final Uri generatedUri = globals.fs.currentDirectory
Dan Field's avatar
Dan Field committed
622 623
        .childDirectory('lib')
        .childFile('generated_plugin_registrant.dart')
624 625 626
        .absolute.uri;
      final Uri generatedImport = packageConfig.toPackageUri(generatedUri);
      Uri importedEntrypoint = packageConfig.toPackageUri(mainUri);
627 628
      // Special handling for entrypoints that are not under lib, such as test scripts.
      if (importedEntrypoint == null) {
629
        final String parent = globals.fs.file(mainUri).parent.path;
630
        flutterDevices.first.generator.addFileSystemRoot(parent);
631
        flutterDevices.first.generator.addFileSystemRoot(globals.fs.directory('test').absolute.path);
632 633 634 635
        importedEntrypoint = Uri(
          scheme: 'org-dartlang-app',
          path: '/' + mainUri.pathSegments.last,
        );
636
      }
Dan Field's avatar
Dan Field committed
637 638

      final String entrypoint = <String>[
639 640 641 642
        determineLanguageVersion(
          globals.fs.file(mainUri),
          packageConfig[flutterProject.manifest.appName],
        ),
643 644 645
        '// Flutter web bootstrap script for $importedEntrypoint.',
        '',
        "import 'dart:ui' as ui;",
646
        "import 'dart:async';",
647 648
        '',
        "import '$importedEntrypoint' as entrypoint;",
Dan Field's avatar
Dan Field committed
649
        if (hasWebPlugins)
650
          "import 'package:flutter_web_plugins/flutter_web_plugins.dart';",
Dan Field's avatar
Dan Field committed
651
        if (hasWebPlugins)
652 653
          "import '$generatedImport';",
        '',
654 655
        'typedef _UnaryFunction = dynamic Function(List<String> args);',
        'typedef _NullaryFunction = dynamic Function();',
Dan Field's avatar
Dan Field committed
656 657
        'Future<void> main() async {',
        if (hasWebPlugins)
658
          '  registerPlugins(webPluginRegistry);',
Dan Field's avatar
Dan Field committed
659
        '  await ui.webOnlyInitializePlatform();',
660 661 662 663
        '  if (entrypoint.main is _UnaryFunction) {',
        '    return (entrypoint.main as _UnaryFunction)(<String>[]);',
        '  }',
        '  return (entrypoint.main as _NullaryFunction)();',
Dan Field's avatar
Dan Field committed
664
        '}',
665
        '',
Dan Field's avatar
Dan Field committed
666 667 668
      ].join('\n');
      result.writeAsStringSync(entrypoint);
    }
669
    return result.absolute.uri;
Dan Field's avatar
Dan Field committed
670 671
  }

672 673 674 675
  Future<UpdateFSReport> _updateDevFS({bool fullRestart = false}) async {
    final bool isFirstUpload = !assetBundle.wasBuiltOnce();
    final bool rebuildBundle = assetBundle.needsBuild();
    if (rebuildBundle) {
676
      globals.printTrace('Updating assets');
677
      final int result = await assetBundle.build(packagesPath: debuggingOptions.buildInfo.packagesPath);
678 679 680 681
      if (result != 0) {
        return UpdateFSReport(success: false);
      }
    }
682
    final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated(
683 684 685
      lastCompiled: device.devFS.lastCompiled,
      urisToMonitor: device.devFS.sources,
      packagesPath: packagesFilePath,
686
      packageConfig: device.devFS.lastPackageConfig,
687
    );
688
    final Status devFSStatus = globals.logger.startProgress(
689 690 691 692
      'Syncing files to device ${device.device.name}...',
      timeout: timeoutConfiguration.fastOperation,
    );
    final UpdateFSReport report = await device.devFS.update(
693 694 695 696
      mainUri: await _generateEntrypoint(
        globals.fs.file(mainPath).absolute.uri,
        invalidationResult.packageConfig,
      ),
697 698 699 700 701 702 703 704 705
      target: target,
      bundle: assetBundle,
      firstBuildTime: firstBuildTime,
      bundleFirstUpload: isFirstUpload,
      generator: device.generator,
      fullRestart: fullRestart,
      dillOutputPath: dillOutputPath,
      projectRootPath: projectRootPath,
      pathToReload: getReloadPath(fullRestart: fullRestart),
706 707
      invalidatedFiles: invalidationResult.uris,
      packageConfig: invalidationResult.packageConfig,
708
      trackWidgetCreation: debuggingOptions.buildInfo.trackWidgetCreation,
709 710
    );
    devFSStatus.stop();
711
    globals.printTrace('Synced ${getSizeAsMB(report.syncedBytes)}.');
712 713 714 715 716 717 718 719
    return report;
  }

  @override
  Future<int> attach({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
  }) async {
720 721
    if (_chromiumLauncher != null) {
      final Chromium chrome = await _chromiumLauncher.connectedInstance;
722
      final ChromeTab chromeTab = await chrome.chromeConnection.getTab((ChromeTab chromeTab) {
723
        return !chromeTab.url.startsWith('chrome-extension');
724
      });
725 726 727
      if (chromeTab == null) {
        throwToolExit('Failed to connect to Chrome instance.');
      }
728 729
      _wipConnection = await chromeTab.connect();
    }
730 731
    Uri websocketUri;
    if (supportsServiceProtocol) {
732 733 734 735 736
      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));

737 738 739 740 741 742 743
      void onLogEvent(vmservice.Event event)  {
        final String message = processVmServiceMessage(event);
        globals.printStatus(message);
      }

      _stdOutSub = _vmService.onStdoutEvent.listen(onLogEvent);
      _stdErrSub = _vmService.onStderrEvent.listen(onLogEvent);
744 745
      _extensionEventSub =
          _vmService.onExtensionEvent.listen(printStructuredErrorLog);
746
      try {
747
        await _vmService.streamListen(vmservice.EventStreams.kStdout);
748 749 750 751 752
      } 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 {
753
        await _vmService.streamListen(vmservice.EventStreams.kStderr);
754 755 756
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
757
      }
758
      try {
759
        await _vmService.streamListen(vmservice.EventStreams.kIsolate);
760 761 762
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
763
      }
764 765 766 767 768 769
      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.
      }
770
      unawaited(_vmService.registerService('reloadSources', 'FlutterTools'));
771 772 773 774 775 776
      _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'};
      });

777 778 779 780 781 782 783 784 785 786 787 788
      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();
          }
789
        });
790
      }
791
    }
792
    if (websocketUri != null) {
793 794 795 796 797
      if (debuggingOptions.vmserviceOutFile != null) {
        globals.fs.file(debuggingOptions.vmserviceOutFile)
          ..createSync(recursive: true)
          ..writeAsStringSync(websocketUri.toString());
      }
798
      globals.printStatus('Debug service listening on $websocketUri');
799
    }
800
    appStartedCompleter?.complete();
801 802 803 804 805 806
    connectionInfoCompleter?.complete(DebugConnectionInfo(wsUri: websocketUri));
    if (stayResident) {
      await waitForAppToFinish();
    } else {
      await stopEchoingDeviceLog();
      await exitApp();
807
    }
808 809
    await cleanupAtFinish();
    return 0;
810
  }
811

812 813 814 815
  @override
  bool get supportsCanvasKit => supportsServiceProtocol;

  @override
816
  Future<bool> toggleCanvaskit() async {
817 818 819
    final WebDevFS webDevFS = device.devFS as WebDevFS;
    webDevFS.webAssetServer.canvasKitRendering = !webDevFS.webAssetServer.canvasKitRendering;
    await _wipConnection?.sendCommand('Page.reload');
820
    return webDevFS.webAssetServer.canvasKitRendering;
821 822
  }

823 824 825 826 827
  @override
  Future<void> exitApp() async {
    await device.exitApps();
    appFinished();
  }
828
}