screenshot.dart 4.99 KB
Newer Older
Devon Carew's avatar
Devon Carew committed
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:http/http.dart' as http;
Devon Carew's avatar
Devon Carew committed
8 9
import 'package:path/path.dart' as path;

10
import '../base/common.dart';
11
import '../base/file_system.dart';
12
import '../base/io.dart' hide IOSink;
Devon Carew's avatar
Devon Carew committed
13
import '../base/utils.dart';
14
import '../device.dart';
Devon Carew's avatar
Devon Carew committed
15 16 17
import '../globals.dart';
import '../runner/flutter_command.dart';

18 19 20 21
const String _kOut = 'out';
const String _kSkia = 'skia';
const String _kSkiaServe = 'skiaserve';

Devon Carew's avatar
Devon Carew committed
22 23
class ScreenshotCommand extends FlutterCommand {
  ScreenshotCommand() {
24 25
    argParser.addOption(
      _kOut,
Devon Carew's avatar
Devon Carew committed
26
      abbr: 'o',
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
      help: 'Location to write the screenshot.',
    );
    argParser.addOption(
      _kSkia,
      valueHelp: 'port',
      help: 'Retrieve the last frame rendered by a Flutter app as a Skia picture\n'
        'using the specified diagnostic server port.\n'
        'To find the diagnostic server port number, use "flutter run --verbose"\n'
        'and look for "Diagnostic server listening on" in the output.'
    );
    argParser.addOption(
      _kSkiaServe,
      valueHelp: 'url',
      help: 'Post the picture to a skiaserve debugger at this URL.',
    );
Devon Carew's avatar
Devon Carew committed
42 43 44 45 46 47 48 49 50 51 52
  }

  @override
  String get name => 'screenshot';

  @override
  String get description => 'Take a screenshot from a connected device.';

  @override
  final List<String> aliases = <String>['pic'];

53
  Device device;
Devon Carew's avatar
Devon Carew committed
54 55

  @override
56
  Future<Null> verifyThenRunCommand() async {
57
    if (argResults[_kSkia] != null) {
58 59
      if (argResults[_kOut] != null && argResults[_kSkiaServe] != null)
        throwToolExit('Cannot specify both --$_kOut and --$_kSkiaServe');
60
    } else {
61 62
      if (argResults[_kSkiaServe] != null)
        throwToolExit('Must specify --$_kSkia with --$_kSkiaServe');
63
      device = await findTargetDevice();
64 65 66 67
      if (device == null)
        throwToolExit('Must specify --$_kSkia or have a connected device');
      if (!device.supportsScreenshot && argResults[_kSkia] == null)
        throwToolExit('Screenshot not supported for ${device.name}.');
68
    }
69 70
    return super.verifyThenRunCommand();
  }
Devon Carew's avatar
Devon Carew committed
71 72

  @override
73
  Future<Null> runCommand() async {
Devon Carew's avatar
Devon Carew committed
74
    File outputFile;
75
    if (argResults.wasParsed(_kOut))
76
      outputFile = fs.file(argResults[_kOut]);
Devon Carew's avatar
Devon Carew committed
77

78 79
    if (argResults[_kSkia] != null) {
      return runSkia(outputFile);
Devon Carew's avatar
Devon Carew committed
80
    } else {
81
      return runScreenshot(outputFile);
Devon Carew's avatar
Devon Carew committed
82
    }
83
  }
Devon Carew's avatar
Devon Carew committed
84

85
  Future<Null> runScreenshot(File outputFile) async {
86
    outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'png');
Devon Carew's avatar
Devon Carew committed
87
    try {
88 89
      if (!await device.takeScreenshot(outputFile))
        throwToolExit('Screenshot failed');
Devon Carew's avatar
Devon Carew committed
90
    } catch (error) {
91
      throwToolExit('Error taking screenshot: $error');
Devon Carew's avatar
Devon Carew committed
92
    }
93
    await showOutputFileInfo(outputFile);
Devon Carew's avatar
Devon Carew committed
94
  }
95

96
  Future<Null> runSkia(File outputFile) async {
97 98 99 100
    Uri skpUri = new Uri(scheme: 'http', host: '127.0.0.1',
        port: int.parse(argResults[_kSkia]),
        path: '/skp');

101 102 103 104
    const String errorHelpText =
        'Be sure the --$_kSkia= option specifies the diagnostic server port, not the observatory port.\n'
        'To find the diagnostic server port number, use "flutter run --verbose"\n'
        'and look for "Diagnostic server listening on" in the output.';
105 106 107 108

    http.StreamedResponse skpResponse;
    try {
      skpResponse = await new http.Request('GET', skpUri).send();
109
    } on SocketException catch (e) {
110
      throwToolExit('Skia screenshot failed: $skpUri\n$e\n\n$errorHelpText');
111
    }
112
    if (skpResponse.statusCode != HttpStatus.OK) {
113
      String error = await skpResponse.stream.toStringStream().join();
114
      throwToolExit('Error: $error\n\n$errorHelpText');
115 116 117 118 119 120 121 122 123 124
    }

    if (argResults[_kSkiaServe] != null) {
      Uri skiaserveUri = Uri.parse(argResults[_kSkiaServe]);
      Uri postUri = new Uri.http(skiaserveUri.authority, '/new');
      http.MultipartRequest postRequest = new http.MultipartRequest('POST', postUri);
      postRequest.files.add(new http.MultipartFile(
          'file', skpResponse.stream, skpResponse.contentLength));

      http.StreamedResponse postResponse = await postRequest.send();
125
      if (postResponse.statusCode != HttpStatus.OK)
126
        throwToolExit('Failed to post Skia picture to skiaserve.\n\n$errorHelpText');
127
    } else {
128
      outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'skp');
129 130 131 132 133 134
      IOSink sink = outputFile.openWrite();
      await sink.addStream(skpResponse.stream);
      await sink.close();
      await showOutputFileInfo(outputFile);
      if (await outputFile.length() < 1000) {
        String content = await outputFile.readAsString();
135 136
        if (content.startsWith('{"jsonrpc":"2.0", "error"'))
          throwToolExit('\nIt appears the output file contains an error message, not valid skia output.\n\n$errorHelpText');
137 138 139 140 141 142 143 144
      }
    }
  }

  Future<Null> showOutputFileInfo(File outputFile) async {
    int sizeKB = (await outputFile.length()) ~/ 1000;
    printStatus('Screenshot written to ${path.relative(outputFile.path)} (${sizeKB}kb).');
  }
Devon Carew's avatar
Devon Carew committed
145
}