Skip to content

Commit c4d08b7

Browse files
jmagmanvashworth
andauthored
Use devicectl for screenshots on Xcode 27, remove idevicescreenshot artifact (flutter#189091)
On Xcode 27 use `devicectl device capture screenshot` instead of idevicescreenshot, which stopped working a few years ago in iOS 17 / Xcode 15. This will reach stable after Xcode 27 releases. 1. Add the `devicectl device capture` code for Xcode 27. 2. Change the < Xcode 27 fallback to `toolExit` with: "`flutter screenshot` requires Xcode 27 or higher." Since Xcode 15 is our minimum now as of flutter#180531, `idevicescreenshot` doesn't work with any configuration with latest Flutter so there's no reason to keep around the fallbacks if < Xcode 27. 3. Remove `_iMobileDevice.takeScreenshot` and `idevicescreenshot` artifact. Note I left in the `run_verify_binaries_codesigned_tests` check because the binary will still be shipping in the libimobiledevice tar ball until we remove it from [the recipe](https://flutter.googlesource.com/recipes/+/refs/heads/main/recipes/ios_usb_dependencies/ios-usb-dependencies.py#48). https://github.com/flutter/flutter/blob/cf9e8afe9a5e601158517782b5b824a328bb2c68/dev/bots/suite_runners/run_verify_binaries_codesigned_tests.dart#L154 Related to flutter#6118 Fixes flutter#128598 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Victoria Ashworth <[email protected]>
1 parent fc53280 commit c4d08b7

10 files changed

Lines changed: 414 additions & 121 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,10 @@ enum HostArtifact {
161161

162162
iosDeploy('ios-deploy'),
163163
idevicesyslog('idevicesyslog'),
164-
idevicescreenshot('idevicescreenshot'),
165164
iproxy('iproxy'),
166165

166+
idevicescreenshot('idevicescreenshot'),
167+
167168
/// The root of the sky_engine package.
168169
skyEnginePath('sky_engine'),
169170

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ class ScreenshotCommand extends FlutterCommand {
125125

126126
try {
127127
await device!.takeScreenshot(outputFile);
128+
} on ToolExit {
129+
rethrow;
128130
} on Exception catch (error) {
129131
throwToolExit('Error taking screenshot: $error');
130132
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ class IosUsbArtifacts extends CachedArtifact {
823823
// used for additional download checks below, so we can re-download if they are
824824
// missing.
825825
static const _kExecutables = <String, List<String>>{
826-
'libimobiledevice': <String>['idevicescreenshot', 'idevicesyslog'],
826+
'libimobiledevice': <String>['idevicesyslog'],
827827
'libusbmuxd': <String>['iproxy'],
828828
};
829829

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -991,6 +991,60 @@ class IOSCoreDeviceControl {
991991
IOSCoreDeviceRunningProcess.fromJson(processObject),
992992
];
993993
}
994+
995+
/// Captures a screenshot from the device and saves it to the destination.
996+
///
997+
/// Returns true if successfully able to take screenshot.
998+
Future<bool> takeScreenshot({required String deviceId, required String destination}) async {
999+
if (!_xcode.isDevicectlInstalled) {
1000+
_logger.printError('devicectl is not installed.');
1001+
return false;
1002+
}
1003+
1004+
final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('core_devices.');
1005+
final File output = tempDirectory.childFile('screenshot_results.json');
1006+
output.createSync();
1007+
1008+
final command = <String>[
1009+
..._xcode.xcrunCommand(),
1010+
'devicectl',
1011+
'device',
1012+
'capture',
1013+
'screenshot',
1014+
'--device',
1015+
deviceId,
1016+
'--destination',
1017+
destination,
1018+
'--json-output',
1019+
output.path,
1020+
];
1021+
1022+
try {
1023+
await _processUtils.run(command, throwOnError: true);
1024+
final String stringOutput = output.readAsStringSync();
1025+
1026+
try {
1027+
final Object? decoded = json.decode(stringOutput);
1028+
if (decoded is Map<String, Object?>) {
1029+
final Object? decodeResult = decoded['info'];
1030+
if (decodeResult is Map<String, Object?> && decodeResult['outcome'] == 'success') {
1031+
return true;
1032+
}
1033+
}
1034+
_logger.printError('devicectl returned unexpected JSON response: $stringOutput');
1035+
return false;
1036+
} on FormatException {
1037+
_logger.printError('devicectl returned non-JSON response: $stringOutput');
1038+
return false;
1039+
}
1040+
} finally {
1041+
try {
1042+
tempDirectory.deleteSync(recursive: true);
1043+
} on FileSystemException {
1044+
// Ignore.
1045+
}
1046+
}
1047+
}
9941048
}
9951049

9961050
class IOSCoreDevice {

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

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,8 +1073,7 @@ class IOSDevice extends Device {
10731073
// However, it doesn't work reliably until Xcode 26.
10741074
// Use LLDB if Xcode version is greater than 26 and the feature is enabled.
10751075
final Version? xcodeVersion = globals.xcode?.currentVersion;
1076-
final bool lldbFeatureEnabled = featureFlags.isLLDBDebuggingEnabled;
1077-
if (xcodeVersion != null && xcodeVersion.major >= 26 && lldbFeatureEnabled) {
1076+
if (xcodeVersion != null && xcodeVersion.major >= 26 && featureFlags.isLLDBDebuggingEnabled) {
10781077
final DeviceLogReader deviceLogReader = getLogReader(
10791078
app: package,
10801079
usingCISystem: debuggingOptions.usingCISystem,
@@ -1323,17 +1322,42 @@ class IOSDevice extends Device {
13231322

13241323
@override
13251324
bool get supportsScreenshot {
1326-
if (isCoreDevice) {
1327-
// `idevicescreenshot` stopped working with iOS 17 / Xcode 15
1328-
// (https://github.com/flutter/flutter/issues/128598).
1329-
return false;
1325+
final Version? xcodeVersion = globals.xcode?.currentVersion;
1326+
if (isCoreDevice && xcodeVersion != null && xcodeVersion.major >= 27) {
1327+
return globals.xcode!.isDevicectlInstalled;
13301328
}
1331-
return _iMobileDevice.isInstalled;
1329+
return false;
13321330
}
13331331

13341332
@override
13351333
Future<void> takeScreenshot(File outputFile) async {
1336-
await _iMobileDevice.takeScreenshot(outputFile, id, connectionInterface);
1334+
final Version? xcodeVersion = globals.xcode?.currentVersion;
1335+
if (isCoreDevice && xcodeVersion != null && xcodeVersion.major >= 27) {
1336+
var success = false;
1337+
try {
1338+
success = await _coreDeviceControl.takeScreenshot(
1339+
deviceId: id,
1340+
destination: outputFile.path,
1341+
);
1342+
} on Exception catch (error) {
1343+
final errorMessage = error.toString();
1344+
if (errorMessage.contains('CoreDeviceError error 4000') ||
1345+
errorMessage.contains('CoreDeviceError error 4016') ||
1346+
errorMessage.contains('RemotePairingError error 2') ||
1347+
errorMessage.contains('Connection was invalidated')) {
1348+
throwToolExit(
1349+
'Failed to establish a connection to the device. '
1350+
'Please make sure the device is available and try again.',
1351+
);
1352+
}
1353+
throwToolExit('Failed to take screenshot with devicectl: $error');
1354+
}
1355+
if (success) {
1356+
return;
1357+
}
1358+
throwToolExit('Failed to take screenshot with devicectl.');
1359+
}
1360+
throwToolExit('flutter screenshot requires Xcode 27 or higher.');
13371361
}
13381362

13391363
@override

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

Lines changed: 1 addition & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,8 @@ class IMobileDevice {
7979
required ProcessManager processManager,
8080
required Logger logger,
8181
}) : _idevicesyslogPath = artifacts.getHostArtifact(HostArtifact.idevicesyslog).path,
82-
_idevicescreenshotPath = artifacts.getHostArtifact(HostArtifact.idevicescreenshot).path,
8382
_dyLdLibEntry = cache.dyLdLibEntry,
84-
_processUtils = ProcessUtils(logger: logger, processManager: processManager),
85-
_processManager = processManager;
83+
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
8684

8785
/// Create an [IMobileDevice] for testing.
8886
factory IMobileDevice.test({required ProcessManager processManager}) {
@@ -96,13 +94,9 @@ class IMobileDevice {
9694
}
9795

9896
final String _idevicesyslogPath;
99-
final String _idevicescreenshotPath;
10097
final MapEntry<String, String> _dyLdLibEntry;
101-
final ProcessManager _processManager;
10298
final ProcessUtils _processUtils;
10399

104-
late final bool isInstalled = _processManager.canRun(_idevicescreenshotPath);
105-
106100
/// Starts `idevicesyslog` and returns the running process.
107101
Future<Process> startLogger(String deviceID, bool isWirelesslyConnected) {
108102
return _processUtils.start(<String>[
@@ -112,25 +106,6 @@ class IMobileDevice {
112106
if (isWirelesslyConnected) '--network',
113107
], environment: Map<String, String>.fromEntries(<MapEntry<String, String>>[_dyLdLibEntry]));
114108
}
115-
116-
/// Captures a screenshot to the specified outputFile.
117-
Future<void> takeScreenshot(
118-
File outputFile,
119-
String deviceID,
120-
DeviceConnectionInterface interfaceType,
121-
) {
122-
return _processUtils.run(
123-
<String>[
124-
_idevicescreenshotPath,
125-
outputFile.path,
126-
'--udid',
127-
deviceID,
128-
if (interfaceType == DeviceConnectionInterface.wireless) '--network',
129-
],
130-
throwOnError: true,
131-
environment: Map<String, String>.fromEntries(<MapEntry<String, String>>[_dyLdLibEntry]),
132-
);
133-
}
134109
}
135110

136111
Future<XcodeBuildResult> buildXcodeProject({

‎packages/flutter_tools/test/general.shard/cache_test.dart‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -993,13 +993,12 @@ void main() {
993993
platform: FakePlatform(operatingSystem: 'macos'),
994994
);
995995
iosUsbArtifacts.location.createSync();
996-
final File ideviceScreenshotFile = iosUsbArtifacts.location.childFile('idevicescreenshot')
996+
final File ideviceSyslogFile = iosUsbArtifacts.location.childFile('idevicesyslog')
997997
..createSync();
998-
iosUsbArtifacts.location.childFile('idevicesyslog').createSync();
999998

1000999
expect(iosUsbArtifacts.isUpToDateInner(fileSystem), true);
10011000

1002-
ideviceScreenshotFile.deleteSync();
1001+
ideviceSyslogFile.deleteSync();
10031002

10041003
expect(iosUsbArtifacts.isUpToDateInner(fileSystem), false);
10051004
},

‎packages/flutter_tools/test/general.shard/ios/core_devices_test.dart‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -953,6 +953,16 @@ void main() {
953953
expect(logger.errorText, contains('devicectl is not installed.'));
954954
expect(status, isFalse);
955955
});
956+
957+
testWithoutContext('fails to take screenshot', () async {
958+
final bool status = await deviceControl.takeScreenshot(
959+
deviceId: 'device-id',
960+
destination: '/path/to/screenshot.png',
961+
);
962+
expect(fakeProcessManager, hasNoRemainingExpectations);
963+
expect(logger.errorText, contains('devicectl is not installed.'));
964+
expect(status, isFalse);
965+
});
956966
});
957967
});
958968

@@ -3887,6 +3897,116 @@ invalid JSON
38873897
expect(logger.traceText, contains('Error reading output file'));
38883898
});
38893899
});
3900+
3901+
group('take screenshot', () {
3902+
const deviceId = 'device-id';
3903+
const destination = '/path/to/screenshot.png';
3904+
3905+
testWithoutContext('Successful screenshot', () async {
3906+
const deviceControlOutput =
3907+
'''
3908+
{
3909+
"info" : {
3910+
"arguments" : [
3911+
"devicectl",
3912+
"device",
3913+
"capture",
3914+
"screenshot",
3915+
"--device",
3916+
"$deviceId",
3917+
"--destination",
3918+
"$destination"
3919+
],
3920+
"outcome" : "success"
3921+
}
3922+
}
3923+
''';
3924+
final File tempFile = fileSystem.systemTempDirectory
3925+
.childDirectory('core_devices.rand0')
3926+
.childFile('screenshot_results.json');
3927+
fakeProcessManager.addCommand(
3928+
FakeCommand(
3929+
command: <String>[
3930+
'xcrun',
3931+
'devicectl',
3932+
'device',
3933+
'capture',
3934+
'screenshot',
3935+
'--device',
3936+
deviceId,
3937+
'--destination',
3938+
destination,
3939+
'--json-output',
3940+
tempFile.path,
3941+
],
3942+
onRun: (_) {
3943+
tempFile.writeAsStringSync(deviceControlOutput);
3944+
},
3945+
),
3946+
);
3947+
3948+
final bool success = await deviceControl.takeScreenshot(
3949+
deviceId: deviceId,
3950+
destination: destination,
3951+
);
3952+
expect(success, isTrue);
3953+
expect(fakeProcessManager, hasNoRemainingExpectations);
3954+
expect(tempFile, isNot(exists));
3955+
});
3956+
3957+
testWithoutContext('failed screenshot', () async {
3958+
const deviceControlOutput =
3959+
'''
3960+
{
3961+
"info" : {
3962+
"arguments" : [
3963+
"devicectl",
3964+
"device",
3965+
"capture",
3966+
"screenshot",
3967+
"--device",
3968+
"$deviceId",
3969+
"--destination",
3970+
"$destination"
3971+
],
3972+
"outcome" : "failure"
3973+
}
3974+
}
3975+
''';
3976+
final File tempFile = fileSystem.systemTempDirectory
3977+
.childDirectory('core_devices.rand0')
3978+
.childFile('screenshot_results.json');
3979+
fakeProcessManager.addCommand(
3980+
FakeCommand(
3981+
command: <String>[
3982+
'xcrun',
3983+
'devicectl',
3984+
'device',
3985+
'capture',
3986+
'screenshot',
3987+
'--device',
3988+
deviceId,
3989+
'--destination',
3990+
destination,
3991+
'--json-output',
3992+
tempFile.path,
3993+
],
3994+
onRun: (_) {
3995+
tempFile.writeAsStringSync(deviceControlOutput);
3996+
},
3997+
),
3998+
);
3999+
4000+
final bool success = await deviceControl.takeScreenshot(
4001+
deviceId: deviceId,
4002+
destination: destination,
4003+
);
4004+
expect(success, isFalse);
4005+
expect(fakeProcessManager, hasNoRemainingExpectations);
4006+
expect(tempFile, isNot(exists));
4007+
expect(logger.errorText, contains('devicectl returned unexpected JSON response'));
4008+
});
4009+
});
38904010
});
38914011
}
38924012

@@ -3898,6 +4018,7 @@ class FakeIOSCoreDeviceControl extends Fake implements IOSCoreDeviceControl {
38984018
this.launchResult,
38994019
this.terminateSuccess = true,
39004020
this.runningProcesses = const <IOSCoreDeviceRunningProcess>[],
4021+
this.takeScreenshotSuccess = true,
39014022
});
39024023

39034024
bool installSuccess;
@@ -3908,6 +4029,12 @@ class FakeIOSCoreDeviceControl extends Fake implements IOSCoreDeviceControl {
39084029
int? processTerminated;
39094030
List<IOSCoreDeviceRunningProcess> runningProcesses;
39104031
bool get terminateProcessCalled => processTerminated != null;
4032+
bool takeScreenshotSuccess;
4033+
4034+
@override
4035+
Future<bool> takeScreenshot({required String deviceId, required String destination}) async {
4036+
return takeScreenshotSuccess;
4037+
}
39114038

39124039
@override
39134040
Future<List<IOSCoreDevice>> getCoreDevices({

0 commit comments

Comments
 (0)