Skip to content

Commit 161c1cd

Browse files
committed
[flutter_tools] Add flutter capture command with screenshot/recording subcommands
Implements `flutter capture screenshot` and `flutter capture recording` as the unified interface for device screenshots and screen recording. - ScreenRecording handle with stop()/done for clean signal handling - Android: adb screenrecord with 180s clamp, exit code check, cleanup - iOS sim: simctl recordVideo with LineSplitter + 10s start timeout - iOS device: devicectl with --json-output outcome verification - macOS: screencapture -v with -V duration flag - Command-agnostic error messages for Xcode version checks - flutter screenshot kept as hidden alias Fixes flutter#190587
1 parent 4e9c63a commit 161c1cd

18 files changed

Lines changed: 2345 additions & 219 deletions

‎packages/flutter_tools/lib/executable.dart‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import 'src/commands/analyze.dart';
2424
import 'src/commands/assemble.dart';
2525
import 'src/commands/attach.dart';
2626
import 'src/commands/build.dart';
27+
import 'src/commands/capture.dart';
2728
import 'src/commands/channel.dart';
2829
import 'src/commands/clean.dart';
2930
import 'src/commands/config.dart';
@@ -277,6 +278,7 @@ List<FlutterCommand> generateCommands({
277278
toolContext: toolDependencies.toolContext,
278279
verboseHelp: verboseHelp,
279280
),
281+
CaptureCommand(toolContext: toolDependencies.toolContext),
280282
ChannelCommand(verboseHelp: verboseHelp, toolContext: toolDependencies.toolContext),
281283
CleanCommand(
282284
extensionCleanManager: toolDependencies.extensionCleanManager,

‎packages/flutter_tools/lib/src/android/android_device.dart‎

Lines changed: 146 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -808,15 +808,113 @@ class AndroidDevice extends Device {
808808
@override
809809
bool get supportsScreenshot => true;
810810

811+
@override
812+
bool get supportsScreenRecording => true;
813+
811814
@override
812815
Future<void> takeScreenshot(File outputFile) async {
813816
const remotePath = '/data/local/tmp/flutter_screenshot.png';
814-
await runAdbCheckedAsync(<String>['shell', 'screencap', '-p', remotePath]);
815-
await _processUtils.run(
816-
adbCommandForDevice(<String>['pull', remotePath, outputFile.path]),
817-
throwOnError: true,
817+
try {
818+
await runAdbCheckedAsync(<String>['shell', 'screencap', '-p', remotePath]);
819+
final RunResult pullResult = await _processUtils.run(
820+
adbCommandForDevice(<String>['pull', remotePath, outputFile.path]),
821+
);
822+
if (pullResult.exitCode != 0) {
823+
final String errorMsg = pullResult.stderr.trim().isNotEmpty
824+
? pullResult.stderr.trim()
825+
: pullResult.stdout.trim();
826+
throwToolExit('Failed to pull screenshot from device: $errorMsg');
827+
}
828+
} on ProcessException catch (error) {
829+
throwToolExit('Failed to take screenshot: $error');
830+
} finally {
831+
try {
832+
await _processUtils.run(adbCommandForDevice(<String>['shell', 'rm', remotePath]));
833+
} on Exception catch (error) {
834+
_logger.printTrace('Failed to clean up remote screenshot: $error');
835+
}
836+
}
837+
}
838+
839+
/// Records the device screen to [outputFile] using `adb screenrecord`.
840+
///
841+
/// The recording is stored on the device at a temporary path, then pulled
842+
/// to the host via `adb pull`. The temporary file is always cleaned up.
843+
///
844+
/// [duration] is clamped to 1–180 seconds (the `adb screenrecord` platform
845+
/// limit). When null, defaults to 180 seconds (the maximum). If the output
846+
/// path is not writable on the host, `adb pull` will throw.
847+
///
848+
/// See: https://developer.android.com/tools/adb#screenrecord
849+
@override
850+
Future<ScreenRecording> startScreenRecording(File outputFile, {Duration? duration}) async {
851+
// https://developer.android.com/tools/adb#screenrecord
852+
const maxAdbSeconds = 180;
853+
if (duration != null && duration.inSeconds > maxAdbSeconds) {
854+
_logger.printWarning(
855+
'Android screen recording has a maximum limit of 180 seconds. '
856+
'Recording will be clamped to 180 seconds.',
857+
);
858+
}
859+
final effectiveDuration = duration != null
860+
? Duration(seconds: duration.inSeconds.clamp(1, maxAdbSeconds))
861+
: const Duration(seconds: maxAdbSeconds);
862+
// Temporary path on the Android device; /data/local/tmp/ is writable by
863+
// the shell user on all API levels that support screenrecord (19+).
864+
const remotePath = '/data/local/tmp/flutter_recording.mp4';
865+
final args = <String>[
866+
'shell',
867+
'screenrecord',
868+
'--time-limit',
869+
'${effectiveDuration.inSeconds}',
870+
remotePath,
871+
];
872+
final Process process = await _processUtils.start(adbCommandForDevice(args));
873+
unawaited(process.stdout.drain<void>());
874+
final Future<String> stderrFuture = process.stderr.transform(utf8AllowMalformed.decoder).join();
875+
876+
Future<void> runRecording() async {
877+
try {
878+
final int recordExitCode = await process.exitCode;
879+
final String stderr = await stderrFuture;
880+
const allowedExitCodes = <int>{0, 130, 143, -2, -15};
881+
final bool isAllowedExitCode =
882+
allowedExitCodes.contains(recordExitCode) ||
883+
(_platform.isWindows && recordExitCode == -1) ||
884+
_allowHeapCorruptionOnWindows(recordExitCode, _platform);
885+
if (!isAllowedExitCode) {
886+
final errorMsg = stderr.trim().isNotEmpty
887+
? 'screenrecord failed with exit code $recordExitCode: ${stderr.trim()}'
888+
: 'screenrecord failed with exit code $recordExitCode.';
889+
throwToolExit(errorMsg);
890+
}
891+
final RunResult pullResult = await _processUtils.run(
892+
adbCommandForDevice(<String>['pull', remotePath, outputFile.path]),
893+
);
894+
if (pullResult.exitCode != 0) {
895+
final String errorMsg = pullResult.stderr.trim().isNotEmpty
896+
? pullResult.stderr.trim()
897+
: pullResult.stdout.trim();
898+
throwToolExit('Failed to pull screen recording from device: $errorMsg');
899+
}
900+
} on ProcessException catch (error) {
901+
throwToolExit('Failed to pull screen recording from device: $error');
902+
} finally {
903+
try {
904+
await _processUtils.run(adbCommandForDevice(<String>['shell', 'rm', remotePath]));
905+
} on Exception catch (error) {
906+
_logger.printTrace('Failed to clean up remote screen recording at $remotePath: $error');
907+
}
908+
}
909+
}
910+
911+
return _AndroidScreenRecording(
912+
process,
913+
runRecording(),
914+
processUtils: _processUtils,
915+
adbCommandForDevice: adbCommandForDevice,
916+
platform: _platform,
818917
);
819-
await runAdbCheckedAsync(<String>['shell', 'rm', remotePath]);
820918
}
821919

822920
@override
@@ -831,6 +929,49 @@ class AndroidDevice extends Device {
831929
}
832930
}
833931

932+
class _AndroidScreenRecording implements ScreenRecording {
933+
_AndroidScreenRecording(
934+
this._process,
935+
this.done, {
936+
required this._processUtils,
937+
required this._adbCommandForDevice,
938+
required this._platform,
939+
});
940+
941+
final Process _process;
942+
final ProcessUtils _processUtils;
943+
final List<String> Function(List<String>) _adbCommandForDevice;
944+
final Platform _platform;
945+
946+
@override
947+
final Future<void> done;
948+
949+
@override
950+
Future<void> stop() async {
951+
if (_platform.isWindows) {
952+
// adb on Windows cannot forward SIGINT via process signal. Send SIGINT directly
953+
// to the on-device screenrecord process to ensure the MP4 moov atom is finalized.
954+
try {
955+
await _processUtils.run(
956+
_adbCommandForDevice(<String>['shell', 'pkill', '-2', 'screenrecord']),
957+
);
958+
} on Exception {
959+
// Best effort: if pkill fails or is unavailable, fallback to process kill below.
960+
}
961+
await _process.exitCode.timeout(
962+
const Duration(seconds: 2),
963+
onTimeout: () {
964+
_process.kill();
965+
return -1;
966+
},
967+
);
968+
} else {
969+
ProcessSignal.sigint.kill(_process);
970+
}
971+
await done;
972+
}
973+
}
974+
834975
Map<String, String> parseAdbDeviceProperties(String str) {
835976
final properties = <String, String>{};
836977
final propertyExp = RegExp(r'\[(.*?)\]: \[(.*?)\]');
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'dart:async';
6+
7+
import '../base/common.dart';
8+
import '../base/file_system.dart';
9+
import '../base/io.dart';
10+
import '../base/logger.dart';
11+
import '../base/signals.dart';
12+
import '../base/utils.dart';
13+
import '../context/tool_context.dart';
14+
import '../device.dart';
15+
import '../runner/flutter_command.dart';
16+
import 'screenshot.dart';
17+
18+
const String _kOut = 'out';
19+
const String _kDuration = 'duration';
20+
21+
/// The `flutter capture` command, which allows capturing screenshots and screen
22+
/// recordings from connected devices.
23+
class CaptureCommand extends FlutterCommand {
24+
CaptureCommand({required super.toolContext}) {
25+
addSubcommand(CaptureScreenshotCommand(toolContext: toolContext));
26+
addSubcommand(CaptureRecordingCommand(toolContext: toolContext));
27+
}
28+
29+
@override
30+
ToolContext get toolContext => super.toolContext!;
31+
32+
@override
33+
String get name => 'capture';
34+
35+
@override
36+
String get description => 'Capture a screenshot or screen recording from a connected device.';
37+
38+
@override
39+
String get category => FlutterCommandCategory.tools;
40+
41+
@override
42+
Future<FlutterCommandResult> runCommand() async => FlutterCommandResult.fail();
43+
}
44+
45+
/// The `flutter capture screenshot` command, which captures a screenshot from a
46+
/// connected device or VM Service.
47+
class CaptureScreenshotCommand extends ScreenshotCommand {
48+
CaptureScreenshotCommand({required super.toolContext, super.vmServiceConnector});
49+
50+
@override
51+
bool get hidden => false;
52+
53+
@override
54+
List<String> get aliases => const <String>[];
55+
}
56+
57+
/// The `flutter capture recording` command, which records the screen of a
58+
/// connected device.
59+
class CaptureRecordingCommand extends FlutterCommand {
60+
CaptureRecordingCommand({required super.toolContext}) {
61+
argParser.addOption(
62+
_kOut,
63+
abbr: 'o',
64+
valueHelp: 'path/to/file',
65+
help: 'Location to write the recording.',
66+
);
67+
argParser.addOption(
68+
_kDuration,
69+
valueHelp: 'seconds',
70+
help:
71+
'Maximum recording duration in seconds. '
72+
'If not specified, recording continues until Ctrl-C is pressed. '
73+
'On Android, duration is limited to a maximum of 180 seconds. '
74+
'On macOS, the entire screen is recorded.',
75+
);
76+
registerOptionBundle(const DeviceDiscoveryOptionsBundle());
77+
}
78+
79+
@override
80+
ToolContext get toolContext => super.toolContext!;
81+
82+
@override
83+
String get name => 'recording';
84+
85+
@override
86+
String get description => 'Record the screen of a connected device.';
87+
88+
@override
89+
final String category = FlutterCommandCategory.tools;
90+
91+
@override
92+
bool get refreshWirelessDevices => true;
93+
94+
Device? _device;
95+
Duration? _duration;
96+
97+
@override
98+
Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) async {
99+
final String? durationStr = stringArg(_kDuration);
100+
if (durationStr != null) {
101+
final int? seconds = int.tryParse(durationStr);
102+
if (seconds == null || seconds <= 0) {
103+
throwToolExit('Invalid duration: "$durationStr". Must be a positive integer.');
104+
}
105+
_duration = Duration(seconds: seconds);
106+
}
107+
return super.verifyThenRunCommand(commandPath);
108+
}
109+
110+
@override
111+
Future<void> validateCommand() async {
112+
await super.validateCommand();
113+
_device = await findTargetDevice(includeDevicesUnsupportedByProject: true);
114+
if (_device == null) {
115+
throwToolExit('No connected device found.');
116+
}
117+
if (!_device!.supportsScreenRecording) {
118+
throwToolExit('Screen recording not supported for ${_device!.displayName}.');
119+
}
120+
}
121+
122+
@override
123+
Future<FlutterCommandResult> runCommand() async {
124+
final ToolContext(
125+
:FileSystem fs,
126+
:Logger logger,
127+
:FileSystemUtils fileSystemUtils,
128+
:Signals signals,
129+
) = toolContext;
130+
131+
final File outputFile = argResults?.wasParsed(_kOut) == true
132+
? fs.file(stringArg(_kOut))
133+
: fileSystemUtils.getUniqueFile(fs.currentDirectory, 'flutter', 'mp4');
134+
135+
if (_duration != null) {
136+
logger.printStatus(
137+
'Recording ${_device!.displayName} for ${_duration!.inSeconds} seconds...',
138+
);
139+
} else {
140+
logger.printStatus('Recording ${_device!.displayName}... Press Ctrl-C to stop.');
141+
}
142+
143+
final ScreenRecording recording = await _device!.startScreenRecording(
144+
outputFile,
145+
duration: _duration,
146+
);
147+
final commandComplete = Completer<void>();
148+
Future<void>? stopFuture;
149+
Future<void> stopRecording(ProcessSignal _) async {
150+
try {
151+
stopFuture ??= recording.stop();
152+
await stopFuture;
153+
await commandComplete.future;
154+
} on Exception catch (error) {
155+
logger.printTrace('Error stopping screen recording: $error');
156+
}
157+
}
158+
159+
final Object sigintToken = signals.addHandler(ProcessSignal.sigint, stopRecording);
160+
final Object sigtermToken = signals.addHandler(ProcessSignal.sigterm, stopRecording);
161+
try {
162+
await recording.done;
163+
if (!outputFile.existsSync() || outputFile.lengthSync() == 0) {
164+
throwToolExit(
165+
'Recording file was not created, ensure path is valid\n'
166+
'Path provided: "${outputFile.path}"',
167+
);
168+
}
169+
logger.printStatus(
170+
'Recording written to ${fs.path.relative(outputFile.path)} (${getSizeAsPlatformMB(outputFile.lengthSync())}).',
171+
);
172+
} finally {
173+
commandComplete.complete();
174+
await signals.removeHandler(ProcessSignal.sigint, sigintToken);
175+
await signals.removeHandler(ProcessSignal.sigterm, sigtermToken);
176+
}
177+
178+
return FlutterCommandResult.success();
179+
}
180+
}

0 commit comments

Comments
 (0)