run.dart 17.8 KB
Newer Older
1 2 3 4 5 6
// Copyright 2015 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 8
import 'package:args/command_runner.dart';

9
import '../base/common.dart';
10
import '../base/file_system.dart';
11
import '../base/time.dart';
12
import '../base/utils.dart';
13
import '../build_info.dart';
14
import '../cache.dart';
15
import '../device.dart';
16
import '../features.dart';
17
import '../globals.dart';
18
import '../project.dart';
19
import '../reporting/reporting.dart';
20
import '../resident_runner.dart';
21 22
import '../run_cold.dart';
import '../run_hot.dart';
23
import '../runner/flutter_command.dart';
24
import '../tracing.dart';
25
import '../version.dart';
26
import '../web/web_runner.dart';
27
import 'daemon.dart';
28

29
abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
30
  // Used by run and drive commands.
31 32
  RunCommandBase({ bool verboseHelp = false }) {
    addBuildModeFlags(defaultToRelease: false, verboseHelp: verboseHelp);
33
    usesFlavorOption();
34 35
    argParser
      ..addFlag('trace-startup',
36
        negatable: false,
37
        help: 'Trace application startup, then exit, saving the trace to a file.',
38
      )
39 40
      ..addFlag('verbose-system-logs',
        negatable: false,
41
        help: 'Include verbose logging from the flutter engine.',
42
      )
43 44
      ..addOption('route',
        help: 'Which route to load when running the app.',
45
      );
46
    usesTargetOption();
47
    usesPortOptions();
48
    usesIpv6Flag();
49
    usesPubOption();
50
    usesTrackWidgetCreation(verboseHelp: verboseHelp);
51
    usesIsolateFilterOption(hide: !verboseHelp);
52
  }
53 54

  bool get traceStartup => argResults['trace-startup'];
55

56
  String get route => argResults['route'];
57
}
58

59
class RunCommand extends RunCommandBase {
60
  RunCommand({ bool verboseHelp = false }) : super(verboseHelp: verboseHelp) {
61
    requiresPubspecYaml();
62
    usesFilesystemOptions(hide: !verboseHelp);
63 64
    argParser
      ..addFlag('start-paused',
65
        negatable: false,
66 67 68
        help: 'Start in a paused mode and wait for a debugger to connect.',
      )
      ..addFlag('enable-software-rendering',
69
        negatable: false,
70 71 72 73
        help: 'Enable rendering using the Skia software backend. '
              'This is useful when testing Flutter on emulators. By default, '
              'Flutter will attempt to either use OpenGL or Vulkan and fall back '
              'to software when neither is available.',
74 75
      )
      ..addFlag('skia-deterministic-rendering',
76
        negatable: false,
77
        help: 'When combined with --enable-software-rendering, provides 100% '
78 79 80
              'deterministic Skia rendering.',
      )
      ..addFlag('trace-skia',
81
        negatable: false,
82
        help: 'Enable tracing of Skia code. This is useful when debugging '
83 84
              'the GPU thread. By default, Flutter will not log skia code.',
      )
85 86 87 88 89
      ..addFlag('trace-systrace',
        negatable: false,
        help: 'Enable tracing to the system tracer. This is only useful on '
              'platforms where such a tracer is available (Android and Fuchsia).',
      )
90 91 92 93 94 95 96
      ..addFlag('dump-skp-on-shader-compilation',
        negatable: false,
        help: 'Automatically dump the skp that triggers new shader compilations. '
              'This is useful for wrting custom ShaderWarmUp to reduce jank. '
              'By default, this is not enabled to reduce the overhead. '
              'This is only available in profile or debug build. ',
      )
97 98 99 100 101 102 103 104
      ..addFlag('await-first-frame-when-tracing',
        defaultsTo: true,
        help: 'Whether to wait for the first frame when tracing startup ("--trace-startup"), '
              'or just dump the trace as soon as the application is running. The first frame '
              'is detected by looking for a Timeline event with the name '
              '"${Tracing.firstUsefulFrameEventName}". '
              'By default, the widgets library\'s binding takes care of sending this event. ',
      )
105
      ..addFlag('use-test-fonts',
106
        negatable: true,
107 108 109 110
        help: 'Enable (and default to) the "Ahem" font. This is a special font '
              'used in tests to remove any dependencies on the font metrics. It '
              'is enabled when you use "flutter test". Set this flag when running '
              'a test using "flutter run" for debugging purposes. This flag is '
111 112 113
              'only available when running in debug mode.',
      )
      ..addFlag('build',
114
        defaultsTo: true,
115 116
        help: 'If necessary, build the app before running.',
      )
117 118 119 120 121 122 123 124 125 126
      ..addOption('dart-flags',
        hide: !verboseHelp,
        help: 'Pass a list of comma separated flags to the Dart instance at '
              'application startup. Flags passed through this option must be '
              'present on the whitelist defined within the Flutter engine. If '
              'a non-whitelisted flag is encountered, the process will be '
              'terminated immediately.\n\n'
              'This flag is not available on the stable channel and is only '
              'applied in debug and profile modes. This option should only '
              'be used for experiments and should not be used by typical users.')
127
      ..addOption('use-application-binary',
128
        hide: !verboseHelp,
129 130 131
        help: 'Specify a pre-built application binary to use when running.',
      )
      ..addOption('project-root',
132
        hide: !verboseHelp,
133 134 135
        help: 'Specify the project root directory.',
      )
      ..addFlag('machine',
136
        hide: !verboseHelp,
137
        negatable: false,
138
        help: 'Handle machine structured JSON command input and provide output '
139 140 141
              'and progress in machine friendly format.',
      )
      ..addFlag('hot',
142 143
        negatable: true,
        defaultsTo: kHotReloadDefault,
144
        help: 'Run with support for hot reloading. Only available for debug mode. Not available with "--trace-startup".',
145 146
      )
      ..addFlag('resident',
147 148 149
        negatable: true,
        defaultsTo: true,
        hide: !verboseHelp,
150 151 152 153 154 155
        help: 'Stay resident after launching the application. Not available with "--trace-startup".',
      )
      ..addOption('pid-file',
        help: 'Specify a file to write the process id to. '
              'You can send SIGUSR1 to trigger a hot reload '
              'and SIGUSR2 to trigger a hot restart.',
156 157 158
      )
      ..addFlag('benchmark',
        negatable: false,
159
        hide: !verboseHelp,
160 161 162
        help: 'Enable a benchmarking mode. This will run the given application, '
              'measure the startup time and the app restart time, write the '
              'results out to "refresh_benchmark.json", and exit. This flag is '
163 164
              'intended for use in generating automated flutter benchmarks.',
      )
165 166 167 168 169
      ..addFlag('disable-service-auth-codes',
        negatable: false,
        hide: !verboseHelp,
        help: 'No longer require an authentication code to connect to the VM '
              'service (not recommended).')
170
      ..addOption(FlutterOptions.kExtraFrontEndOptions, hide: true)
171 172 173 174 175
      ..addOption(FlutterOptions.kExtraGenSnapshotOptions, hide: true)
      ..addMultiOption(FlutterOptions.kEnableExperiment,
        splitCommas: true,
        hide: true,
      );
176 177
  }

178 179 180 181 182 183
  @override
  final String name = 'run';

  @override
  final String description = 'Run your Flutter app on an attached device.';

184
  List<Device> devices;
185

186
  @override
187
  Future<String> get usagePath async {
188
    final String command = await super.usagePath;
189

190
    if (devices == null)
191
      return command;
192
    else if (devices.length > 1)
193 194 195
      return '$command/all';
    else
      return '$command/${getNameForTargetPlatform(await devices[0].targetPlatform)}';
196 197
  }

198
  @override
199
  Future<Map<CustomDimensions, String>> get usageValues async {
200
    String deviceType, deviceOsVersion;
201 202 203 204 205 206 207
    bool isEmulator;

    if (devices == null || devices.isEmpty) {
      deviceType = 'none';
      deviceOsVersion = 'none';
      isEmulator = false;
    } else if (devices.length == 1) {
208 209
      deviceType = getNameForTargetPlatform(await devices[0].targetPlatform);
      deviceOsVersion = await devices[0].sdkNameAndVersion;
210
      isEmulator = await devices[0].isLocalEmulator;
211 212 213
    } else {
      deviceType = 'multiple';
      deviceOsVersion = 'multiple';
214
      isEmulator = false;
215 216
    }
    final String modeName = getBuildInfo().modeName;
217 218 219
    final AndroidProject androidProject = FlutterProject.current().android;
    final IosProject iosProject = FlutterProject.current().ios;
    final List<String> hostLanguage = <String>[];
220

221 222 223 224 225 226 227
    if (androidProject != null && androidProject.existsSync()) {
      hostLanguage.add(androidProject.isKotlin ? 'kotlin' : 'java');
    }
    if (iosProject != null && iosProject.exists) {
      hostLanguage.add(iosProject.isSwift ? 'swift' : 'objc');
    }

228 229 230 231 232 233 234
    return <CustomDimensions, String>{
      CustomDimensions.commandRunIsEmulator: '$isEmulator',
      CustomDimensions.commandRunTargetName: deviceType,
      CustomDimensions.commandRunTargetOsVersion: deviceOsVersion,
      CustomDimensions.commandRunModeName: modeName,
      CustomDimensions.commandRunProjectModule: '${FlutterProject.current().isModule}',
      CustomDimensions.commandRunProjectHostLanguage: hostLanguage.join(','),
235
    };
236 237
  }

238 239 240 241 242 243 244 245 246
  @override
  bool get shouldRunPub {
    // If we are running with a prebuilt application, do not run pub.
    if (runningWithPrebuiltApplication)
      return false;

    return super.shouldRunPub;
  }

247
  bool shouldUseHotMode() {
248
    final bool hotArg = argResults['hot'] ?? false;
249
    final bool shouldUseHotMode = hotArg && !traceStartup;
250
    return getBuildInfo().isDebug && shouldUseHotMode;
251 252
  }

253 254 255
  bool get runningWithPrebuiltApplication =>
      argResults['use-application-binary'] != null;

256
  bool get stayResident => argResults['resident'];
257
  bool get awaitFirstFrameWhenTracing => argResults['await-first-frame-when-tracing'];
258

259
  @override
260
  Future<void> validateCommand() async {
261 262 263 264
    // When running with a prebuilt application, no command validation is
    // necessary.
    if (!runningWithPrebuiltApplication)
      await super.validateCommand();
265 266
    devices = await findAllTargetDevices();
    if (devices == null)
267
      throwToolExit(null);
268 269
    if (deviceManager.hasSpecifiedAllDevices && runningWithPrebuiltApplication)
      throwToolExit('Using -d all with --use-application-binary is not supported');
270 271
  }

272
  DebuggingOptions _createDebuggingOptions() {
273 274
    final BuildInfo buildInfo = getBuildInfo();
    if (buildInfo.isRelease) {
275
      return DebuggingOptions.disabled(buildInfo);
276
    } else {
277
      return DebuggingOptions.enabled(
278
        buildInfo,
279
        startPaused: argResults['start-paused'],
280
        disableServiceAuthCodes: argResults['disable-service-auth-codes'],
281
        dartFlags: argResults['dart-flags'] ?? '',
282
        useTestFonts: argResults['use-test-fonts'],
283
        enableSoftwareRendering: argResults['enable-software-rendering'],
284
        skiaDeterministicRendering: argResults['skia-deterministic-rendering'],
285
        traceSkia: argResults['trace-skia'],
286
        traceSystrace: argResults['trace-systrace'],
287
        dumpSkpOnShaderCompilation: argResults['dump-skp-on-shader-compilation'],
288
        observatoryPort: observatoryPort,
289
        verboseSystemLogs: argResults['verbose-system-logs'],
290 291 292 293
      );
    }
  }

294
  @override
295
  Future<FlutterCommandResult> runCommand() async {
296 297 298 299 300 301
    Cache.releaseLockEarly();

    // Enable hot mode by default if `--no-hot` was not passed and we are in
    // debug mode.
    final bool hotMode = shouldUseHotMode();

302 303
    writePidFile(argResults['pid-file']);

304
    if (argResults['machine']) {
305 306
      if (devices.length > 1)
        throwToolExit('--machine does not support -d all.');
307 308
      final Daemon daemon = Daemon(stdinCommandStream, stdoutCommandResponse,
          notifyingLogger: NotifyingLogger(), logToStdout: true);
309 310
      AppInstance app;
      try {
311
        final String applicationBinaryPath = argResults['use-application-binary'];
312
        app = await daemon.appDomain.startApp(
313
          devices.first, fs.currentDirectory.path, targetFile, route,
314
          _createDebuggingOptions(), hotMode,
315 316 317
          applicationBinary: applicationBinaryPath == null
              ? null
              : fs.file(applicationBinaryPath),
318
          trackWidgetCreation: argResults['track-widget-creation'],
319
          projectRootPath: argResults['project-root'],
320
          packagesFilePath: globalResults['packages'],
321
          dillOutputPath: argResults['output-dill'],
322
          ipv6: ipv6,
323
        );
324 325 326
      } catch (error) {
        throwToolExit(error.toString());
      }
327
      final DateTime appStartedTime = systemClock.now();
328
      final int result = await app.runner.waitForAppToFinish();
329 330
      if (result != 0)
        throwToolExit(null, exitCode: result);
331
      return FlutterCommandResult(
332
        ExitStatus.success,
333
        timingLabelParts: <String>['daemon'],
334 335
        endTimeOverride: appStartedTime,
      );
336 337
    }

338
    if (argResults['dart-flags'] != null && !FlutterVersion.instance.isMaster) {
339 340 341 342
      throw UsageException('--dart-flags is not available on the stable '
                           'channel.', null);
    }

343
    for (Device device in devices) {
344 345 346 347 348
      if (await device.isLocalEmulator) {
        if (await device.supportsHardwareRendering) {
          final bool enableSoftwareRendering = argResults['enable-software-rendering'] == true;
          if (enableSoftwareRendering) {
            printStatus(
349
              'Using software rendering with device ${device.name}. You may get better performance '
350 351 352 353
              'with hardware mode by configuring hardware rendering for your device.'
            );
          } else {
            printStatus(
354
              'Using hardware rendering with device ${device.name}. If you get graphics artifacts, '
355 356 357 358 359 360
              'consider enabling software rendering with "--enable-software-rendering".'
            );
          }
        }

        if (!isEmulatorBuildMode(getBuildMode())) {
361
          throwToolExit('${toTitleCase(getFriendlyModeName(getBuildMode()))} mode is not supported for emulators.');
362 363
        }
      }
364
    }
365

366
    if (hotMode) {
367
      for (Device device in devices) {
368 369
        if (!device.supportsHotReload)
          throwToolExit('Hot reload is not supported by ${device.name}. Run with --no-hot.');
370
      }
371 372
    }

373 374 375 376 377
    List<String> expFlags;
    if (argParser.options.containsKey(FlutterOptions.kEnableExperiment) &&
        argResults[FlutterOptions.kEnableExperiment].isNotEmpty) {
      expFlags = argResults[FlutterOptions.kEnableExperiment];
    }
378
    final List<FlutterDevice> flutterDevices = <FlutterDevice>[];
379
    final FlutterProject flutterProject = FlutterProject.current();
380 381
    for (Device device in devices) {
      final FlutterDevice flutterDevice = await FlutterDevice.create(
382
        device,
383
        flutterProject: flutterProject,
384
        trackWidgetCreation: argResults['track-widget-creation'],
385 386
        fileSystemRoots: argResults['filesystem-root'],
        fileSystemScheme: argResults['filesystem-scheme'],
387
        viewFilter: argResults['isolate-filter'],
388
        experimentalFlags: expFlags,
389
        target: argResults['target'],
390
        buildMode: getBuildMode(),
391
      );
392 393
      flutterDevices.add(flutterDevice);
    }
394 395 396 397 398
    // Only support "web mode" with a single web device due to resident runner
    // refactoring required otherwise.
    final bool webMode = featureFlags.isWebEnabled &&
                         devices.length == 1  &&
                         await devices.single.targetPlatform == TargetPlatform.web_javascript;
399 400

    ResidentRunner runner;
asiva's avatar
asiva committed
401
    final String applicationBinaryPath = argResults['use-application-binary'];
402
    if (hotMode && !webMode) {
403
      runner = HotRunner(
404
        flutterDevices,
405
        target: targetFile,
406
        debuggingOptions: _createDebuggingOptions(),
407
        benchmarkMode: argResults['benchmark'],
asiva's avatar
asiva committed
408 409 410
        applicationBinary: applicationBinaryPath == null
            ? null
            : fs.file(applicationBinaryPath),
411
        projectRootPath: argResults['project-root'],
412
        packagesFilePath: globalResults['packages'],
413
        dillOutputPath: argResults['output-dill'],
414
        stayResident: stayResident,
415
        ipv6: ipv6,
416
      );
417
    } else if (webMode) {
418
      runner = webRunnerFactory.createWebRunner(
419
        devices.single,
420 421 422
        target: targetFile,
        flutterProject: flutterProject,
        ipv6: ipv6,
423
        debuggingOptions: _createDebuggingOptions(),
424
      );
Devon Carew's avatar
Devon Carew committed
425
    } else {
426
      runner = ColdRunner(
427
        flutterDevices,
428
        target: targetFile,
429
        debuggingOptions: _createDebuggingOptions(),
Devon Carew's avatar
Devon Carew committed
430
        traceStartup: traceStartup,
431
        awaitFirstFrameWhenTracing: awaitFirstFrameWhenTracing,
asiva's avatar
asiva committed
432 433 434
        applicationBinary: applicationBinaryPath == null
            ? null
            : fs.file(applicationBinaryPath),
435
        ipv6: ipv6,
436
        stayResident: stayResident,
Devon Carew's avatar
Devon Carew committed
437 438
      );
    }
439

440
    DateTime appStartedTime;
441 442
    // Sync completer so the completing agent attaching to the resident doesn't
    // need to know about analytics.
443 444
    //
    // Do not add more operations to the future.
445
    final Completer<void> appStartedTimeRecorder = Completer<void>.sync();
446
    // This callback can't throw.
447
    unawaited(appStartedTimeRecorder.future.then<void>(
448 449 450 451 452 453 454 455
      (_) {
        appStartedTime = systemClock.now();
        if (stayResident) {
          TerminalHandler(runner)
            ..setupTerminal()
            ..registerSignalHandlers();
        }
      }
456
    ));
457

458
    final int result = await runner.run(
459
      appStartedCompleter: appStartedTimeRecorder,
460 461
      route: route,
    );
462
    if (result != 0) {
463
      throwToolExit(null, exitCode: result);
464
    }
465
    return FlutterCommandResult(
466
      ExitStatus.success,
467
      timingLabelParts: <String>[
468 469
        hotMode ? 'hot' : 'cold',
        getModeName(getBuildMode()),
470
        devices.length == 1
471 472
            ? getNameForTargetPlatform(await devices[0].targetPlatform)
            : 'multiple',
473
        devices.length == 1 && await devices[0].isLocalEmulator ? 'emulator' : null,
474 475 476
      ],
      endTimeOverride: appStartedTime,
    );
Adam Barth's avatar
Adam Barth committed
477 478
  }
}