Skip to content

Commit 1c8dc5b

Browse files
committed
[flutter_tools] Add flutter capture command with image/video subcommands (flutter#190587)
Adds `flutter capture image` and `flutter capture video` for device screenshot and screen recording. Deprecates `flutter screenshot`. Supported platforms: - Android (adb screenrecord, capped at 180s) - iOS simulator (simctl recordVideo with SIGINT-based stop) - iOS device (devicectl, requires Xcode 27+) - macOS (screencapture)
1 parent 5139530 commit 1c8dc5b

10 files changed

Lines changed: 627 additions & 1 deletion

File tree

‎packages/flutter_tools/lib/executable.dart‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import 'src/commands/analyze.dart';
2121
import 'src/commands/assemble.dart';
2222
import 'src/commands/attach.dart';
2323
import 'src/commands/build.dart';
24+
import 'src/commands/capture.dart';
2425
import 'src/commands/channel.dart';
2526
import 'src/commands/clean.dart';
2627
import 'src/commands/config.dart';
@@ -232,6 +233,7 @@ List<FlutterCommand> generateCommands({
232233
processInfo: ProcessInfo(toolDependencies.toolContext.fs),
233234
fileSystem: toolDependencies.toolContext.fs,
234235
),
236+
CaptureCommand(fs: toolDependencies.toolContext.fs),
235237
BuildCommand(
236238
fileSystem: toolDependencies.toolContext.fs,
237239
buildSystem: toolDependencies.buildSystem,

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,9 @@ class AndroidDevice extends Device {
820820
@override
821821
bool get supportsScreenshot => true;
822822

823+
@override
824+
bool get supportsScreenRecording => true;
825+
823826
@override
824827
Future<void> takeScreenshot(File outputFile) async {
825828
const remotePath = '/data/local/tmp/flutter_screenshot.png';
@@ -831,6 +834,36 @@ class AndroidDevice extends Device {
831834
await runAdbCheckedAsync(<String>['shell', 'rm', remotePath]);
832835
}
833836

837+
@override
838+
Future<void> startScreenRecording(
839+
File outputFile, {
840+
Duration? duration,
841+
}) async {
842+
// adb screenrecord caps at 180 seconds.
843+
const maxAdbSeconds = 180;
844+
final effectiveDuration = duration != null
845+
? Duration(seconds: duration.inSeconds.clamp(1, maxAdbSeconds))
846+
: const Duration(seconds: maxAdbSeconds);
847+
const remotePath = '/data/local/tmp/flutter_recording.mp4';
848+
final args = <String>[
849+
'shell', 'screenrecord',
850+
'--time-limit', '${effectiveDuration.inSeconds}',
851+
remotePath,
852+
];
853+
final Process process = await _processManager.start(
854+
adbCommandForDevice(args),
855+
);
856+
try {
857+
await process.exitCode;
858+
} finally {
859+
await _processUtils.run(
860+
adbCommandForDevice(<String>['pull', remotePath, outputFile.path]),
861+
throwOnError: true,
862+
);
863+
await runAdbCheckedAsync(<String>['shell', 'rm', remotePath]);
864+
}
865+
}
866+
834867
@override
835868
bool isSupportedForProject(FlutterProject flutterProject) {
836869
return flutterProject.android.existsSync();
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
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 '../base/common.dart';
6+
import '../base/file_system.dart';
7+
import '../device.dart';
8+
import '../globals.dart' as globals;
9+
import '../runner/flutter_command.dart';
10+
11+
class CaptureCommand extends FlutterCommand {
12+
CaptureCommand({required FileSystem fs}) {
13+
addSubcommand(CaptureImageCommand(fs: fs));
14+
addSubcommand(CaptureVideoCommand(fs: fs));
15+
}
16+
17+
@override
18+
String get name => 'capture';
19+
20+
@override
21+
String get description => 'Capture a screenshot or screen recording from a connected device.';
22+
23+
@override
24+
String get category => FlutterCommandCategory.tools;
25+
26+
@override
27+
Future<FlutterCommandResult> runCommand() async => FlutterCommandResult.fail();
28+
}
29+
30+
const String _kOut = 'out';
31+
32+
class CaptureImageCommand extends FlutterCommand {
33+
CaptureImageCommand({required this.fs}) {
34+
argParser.addOption(
35+
_kOut,
36+
abbr: 'o',
37+
valueHelp: 'path/to/file',
38+
help: 'Location to write the screenshot.',
39+
);
40+
usesDeviceTimeoutOption();
41+
usesDeviceConnectionOption();
42+
}
43+
44+
final FileSystem fs;
45+
46+
@override
47+
String get name => 'image';
48+
49+
@override
50+
String get description => 'Take a screenshot from a connected device.';
51+
52+
@override
53+
final String category = FlutterCommandCategory.tools;
54+
55+
@override
56+
bool get refreshWirelessDevices => true;
57+
58+
Device? _device;
59+
60+
@override
61+
Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) async {
62+
_device = await findTargetDevice(includeDevicesUnsupportedByProject: true);
63+
if (_device == null) {
64+
throwToolExit('No connected device found.');
65+
}
66+
if (!_device!.supportsScreenshot) {
67+
throwToolExit('Screenshot not supported for ${_device!.displayName}.');
68+
}
69+
return super.verifyThenRunCommand(commandPath);
70+
}
71+
72+
@override
73+
Future<FlutterCommandResult> runCommand() async {
74+
final File outputFile = argResults?.wasParsed(_kOut) == true
75+
? fs.file(stringArg(_kOut))
76+
: globals.fsUtils.getUniqueFile(fs.currentDirectory, 'flutter', 'png');
77+
78+
try {
79+
await _device!.takeScreenshot(outputFile);
80+
} on ToolExit {
81+
rethrow;
82+
} on Exception catch (error) {
83+
throwToolExit('Error taking screenshot: $error');
84+
}
85+
86+
if (!fs.file(outputFile.path).existsSync()) {
87+
throwToolExit(
88+
'File was not created, ensure path is valid\n'
89+
'Path provided: "${outputFile.path}"',
90+
);
91+
}
92+
93+
final int sizeKB = outputFile.lengthSync() ~/ 1024;
94+
globals.printStatus(
95+
'Screenshot written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).',
96+
);
97+
return FlutterCommandResult.success();
98+
}
99+
}
100+
101+
class CaptureVideoCommand extends FlutterCommand {
102+
CaptureVideoCommand({required this.fs}) {
103+
argParser.addOption(
104+
_kOut,
105+
abbr: 'o',
106+
valueHelp: 'path/to/file',
107+
help: 'Location to write the recording.',
108+
);
109+
argParser.addOption(
110+
'duration',
111+
abbr: 'd',
112+
valueHelp: 'seconds',
113+
help: 'Maximum recording duration in seconds. '
114+
'If not specified, recording continues until Ctrl-C is pressed.',
115+
);
116+
usesDeviceTimeoutOption();
117+
usesDeviceConnectionOption();
118+
}
119+
120+
final FileSystem fs;
121+
122+
@override
123+
String get name => 'video';
124+
125+
@override
126+
String get description => 'Record the screen of a connected device.';
127+
128+
@override
129+
final String category = FlutterCommandCategory.tools;
130+
131+
@override
132+
bool get refreshWirelessDevices => true;
133+
134+
Device? _device;
135+
136+
@override
137+
Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) async {
138+
_device = await findTargetDevice(includeDevicesUnsupportedByProject: true);
139+
if (_device == null) {
140+
throwToolExit('No connected device found.');
141+
}
142+
if (!_device!.supportsScreenRecording) {
143+
throwToolExit('Screen recording not supported for ${_device!.displayName}.');
144+
}
145+
return super.verifyThenRunCommand(commandPath);
146+
}
147+
148+
@override
149+
Future<FlutterCommandResult> runCommand() async {
150+
final File outputFile = argResults?.wasParsed(_kOut) == true
151+
? fs.file(stringArg(_kOut))
152+
: globals.fsUtils.getUniqueFile(fs.currentDirectory, 'flutter', 'mp4');
153+
154+
Duration? duration;
155+
final String? durationStr = stringArg('duration');
156+
if (durationStr != null) {
157+
final int? seconds = int.tryParse(durationStr);
158+
if (seconds == null || seconds <= 0) {
159+
throwToolExit('Invalid duration: "$durationStr". Must be a positive integer.');
160+
}
161+
duration = Duration(seconds: seconds);
162+
}
163+
164+
if (duration != null) {
165+
globals.printStatus(
166+
'Recording ${_device!.displayName} for ${duration.inSeconds} seconds...',
167+
);
168+
} else {
169+
globals.printStatus(
170+
'Recording ${_device!.displayName}... Press Ctrl-C to stop.',
171+
);
172+
}
173+
174+
try {
175+
await _device!.startScreenRecording(outputFile, duration: duration);
176+
} on ToolExit {
177+
rethrow;
178+
} on Exception catch (error) {
179+
throwToolExit('Error recording screen: $error');
180+
}
181+
182+
if (!fs.file(outputFile.path).existsSync()) {
183+
throwToolExit(
184+
'Recording file was not created, ensure path is valid\n'
185+
'Path provided: "${outputFile.path}"',
186+
);
187+
}
188+
189+
final int sizeKB = outputFile.lengthSync() ~/ 1024;
190+
globals.printStatus(
191+
'Recording written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).',
192+
);
193+
return FlutterCommandResult.success();
194+
}
195+
}

‎packages/flutter_tools/lib/src/commands/screenshot.dart‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,11 @@ class ScreenshotCommand extends FlutterCommand {
6060
String get name => 'screenshot';
6161

6262
@override
63-
String get description => 'Take a screenshot from a connected device.';
63+
String get description =>
64+
'(Deprecated, use "flutter capture image") Take a screenshot from a connected device.';
65+
66+
@override
67+
bool get deprecated => true;
6468

6569
@override
6670
final String category = FlutterCommandCategory.tools;

‎packages/flutter_tools/lib/src/device.dart‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -802,6 +802,9 @@ abstract class Device {
802802
/// application.
803803
bool get supportsScreenshot => false;
804804

805+
/// Whether the device supports recording the screen.
806+
bool get supportsScreenRecording => false;
807+
805808
/// Whether the Flavors feature ('--flavor') is supported for this device.
806809
bool get supportsFlavors => false;
807810

@@ -820,6 +823,20 @@ abstract class Device {
820823

821824
Future<void> takeScreenshot(File outputFile) => Future<void>.error('unimplemented');
822825

826+
/// Starts recording the device screen to [outputFile].
827+
///
828+
/// Recording continues until the returned [Future] completes. The future
829+
/// completes when the recording process exits — either because [duration]
830+
/// elapsed or because the process received a signal (e.g. SIGINT from
831+
/// Ctrl-C).
832+
///
833+
/// [duration] caps the recording length. When null, recording runs until
834+
/// the process is interrupted.
835+
Future<void> startScreenRecording(
836+
File outputFile, {
837+
Duration? duration,
838+
}) => Future<void>.error('unimplemented');
839+
823840
@nonVirtual
824841
@override
825842
// ignore: avoid_equals_and_hash_code_on_mutable_classes
@@ -893,6 +910,7 @@ abstract class Device {
893910
'hotReload': supportsHotReload,
894911
'hotRestart': supportsHotRestart,
895912
'screenshot': supportsScreenshot,
913+
'screenRecording': supportsScreenRecording,
896914
'flutterExit': supportsFlutterExit,
897915
'hardwareRendering': isLocalEmu && await supportsHardwareRendering,
898916
'startPaused': supportsStartPaused,

‎packages/flutter_tools/lib/src/ios/core_devices.dart‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import 'dart:async';
77
import 'package:meta/meta.dart';
88
import 'package:process/process.dart';
99

10+
import '../base/common.dart';
1011
import '../base/error_handling_io.dart';
1112
import '../base/file_system.dart';
1213
import '../base/io.dart';
@@ -1057,6 +1058,27 @@ class IOSCoreDeviceControl {
10571058
}
10581059
}
10591060
}
1061+
1062+
Future<Process> startScreenRecording({
1063+
required String deviceId,
1064+
required String destination,
1065+
}) async {
1066+
if (!_xcode.isDevicectlInstalled) {
1067+
throwToolExit('devicectl is not installed.');
1068+
}
1069+
1070+
return _processUtils.start(<String>[
1071+
..._xcode.xcrunCommand(),
1072+
'devicectl',
1073+
'device',
1074+
'capture',
1075+
'screen-record',
1076+
'--device',
1077+
deviceId,
1078+
'--destination',
1079+
destination,
1080+
]);
1081+
}
10601082
}
10611083

10621084
class IOSCoreDevice {

‎packages/flutter_tools/lib/src/ios/devices.dart‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1420,6 +1420,52 @@ class IOSDevice extends Device {
14201420
throwToolExit('flutter screenshot requires Xcode 27 or higher.');
14211421
}
14221422

1423+
@override
1424+
bool get supportsScreenRecording {
1425+
final Version? xcodeVersion = globals.xcode?.currentVersion;
1426+
if (isCoreDevice && xcodeVersion != null && xcodeVersion.major >= 27) {
1427+
return globals.xcode!.isDevicectlInstalled;
1428+
}
1429+
return false;
1430+
}
1431+
1432+
@override
1433+
Future<void> startScreenRecording(
1434+
File outputFile, {
1435+
Duration? duration,
1436+
}) async {
1437+
final Version? xcodeVersion = globals.xcode?.currentVersion;
1438+
if (isCoreDevice && xcodeVersion != null && xcodeVersion.major >= 27) {
1439+
try {
1440+
final Process process = await _coreDeviceControl.startScreenRecording(
1441+
deviceId: id,
1442+
destination: outputFile.path,
1443+
);
1444+
if (duration != null) {
1445+
await Future.any(<Future<void>>[
1446+
process.exitCode.then((_) {}),
1447+
Future<void>.delayed(duration).then((_) => ProcessSignal.sigint.kill(process)),
1448+
]);
1449+
}
1450+
await process.exitCode;
1451+
return;
1452+
} on Exception catch (error) {
1453+
final errorMessage = error.toString();
1454+
if (errorMessage.contains('CoreDeviceError error 4000') ||
1455+
errorMessage.contains('CoreDeviceError error 4016') ||
1456+
errorMessage.contains('RemotePairingError error 2') ||
1457+
errorMessage.contains('Connection was invalidated')) {
1458+
throwToolExit(
1459+
'Failed to establish a connection to the device. '
1460+
'Please make sure the device is available and try again.',
1461+
);
1462+
}
1463+
throwToolExit('Failed to record screen with devicectl: $error');
1464+
}
1465+
}
1466+
throwToolExit('flutter capture video requires Xcode 27 or higher.');
1467+
}
1468+
14231469
@override
14241470
bool isSupportedForProject(FlutterProject flutterProject) {
14251471
return flutterProject.ios.existsSync();

0 commit comments

Comments
 (0)