1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Copyright 2014 The Flutter 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 'package:meta/meta.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/process.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../build_system/build_system.dart';
import '../build_system/targets/macos.dart';
import '../cache.dart';
import '../flutter_plugins.dart';
import '../globals.dart' as globals;
import '../macos/cocoapod_utils.dart';
import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult;
import '../version.dart';
import 'build_ios_framework.dart';
/// Produces a .framework for integration into a host macOS app. The .framework
/// contains the Flutter engine and framework code as well as plugins. It can
/// be integrated into plain Xcode projects without using or other package
/// managers.
class BuildMacOSFrameworkCommand extends BuildFrameworkCommand {
BuildMacOSFrameworkCommand({
super.flutterVersion,
required super.buildSystem,
required super.verboseHelp,
super.cache,
super.platform,
});
@override
final String name = 'macos-framework';
@override
final String description = 'Produces .xcframeworks for a Flutter project '
'and its plugins for integration into existing, plain macOS Xcode projects.\n'
'This can only be run on macOS hosts.';
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{
DevelopmentArtifact.macOS,
};
@override
Future<FlutterCommandResult> runCommand() async {
final String outputArgument = stringArg('output') ??
globals.fs.path.join(
globals.fs.currentDirectory.path,
'build',
'macos',
'framework',
);
if (outputArgument.isEmpty) {
throwToolExit('--output is required.');
}
if (!project.macos.existsSync()) {
throwToolExit('Project does not support macOS');
}
final Directory outputDirectory =
globals.fs.directory(globals.fs.path.absolute(globals.fs.path.normalize(outputArgument)));
final List<BuildInfo> buildInfos = await getBuildInfos();
displayNullSafetyMode(buildInfos.first);
for (final BuildInfo buildInfo in buildInfos) {
globals.printStatus('Building macOS frameworks in ${getNameForBuildMode(buildInfo.mode)} mode...');
final String xcodeBuildConfiguration = sentenceCase(getNameForBuildMode(buildInfo.mode));
final Directory modeDirectory = outputDirectory.childDirectory(xcodeBuildConfiguration);
if (modeDirectory.existsSync()) {
modeDirectory.deleteSync(recursive: true);
}
if (boolArg('cocoapods') ?? false) {
produceFlutterPodspec(buildInfo.mode, modeDirectory, force: boolArg('force') ?? false);
}
// Build aot, create App.framework and copy FlutterMacOS.framework. Make XCFrameworks.
await _produceAppFramework(buildInfo, modeDirectory);
// Build and copy plugins.
final Directory buildOutput = modeDirectory.childDirectory('macos');
await processPodsIfNeeded(project.macos, getMacOSBuildDirectory(), buildInfo.mode);
if (hasPlugins(project)) {
await _producePlugins(xcodeBuildConfiguration, buildOutput, modeDirectory);
}
globals.logger.printStatus(' └─Moving to ${globals.fs.path.relative(modeDirectory.path)}');
// Delete the intermediaries since they would have been copied into our
// output frameworks.
if (buildOutput.existsSync()) {
buildOutput.deleteSync(recursive: true);
}
}
globals.printStatus('Frameworks written to ${outputDirectory.path}.');
if (hasPlugins(project)) {
// Apps do not generate a FlutterPluginRegistrant.framework. Users will need
// to copy GeneratedPluginRegistrant.swift to their project manually.
final File pluginRegistrantImplementation = project.macos.pluginRegistrantImplementation;
pluginRegistrantImplementation.copySync(outputDirectory.childFile(pluginRegistrantImplementation.basename).path);
globals.printStatus('\nCopy ${globals.fs.path.basename(pluginRegistrantImplementation.path)} into your project.');
}
return FlutterCommandResult.success();
}
/// Create podspec that will download and unzip remote engine assets so host apps can leverage CocoaPods
/// vendored framework caching.
@visibleForTesting
void produceFlutterPodspec(BuildMode mode, Directory modeDirectory, {bool force = false}) {
final Status status = globals.logger.startProgress(' ├─Creating FlutterMacOS.podspec...');
try {
final GitTagVersion gitTagVersion = flutterVersion.gitTagVersion;
if (!force &&
(gitTagVersion.x == null ||
gitTagVersion.y == null ||
gitTagVersion.z == null ||
gitTagVersion.commits != 0)) {
throwToolExit(
'--cocoapods is only supported on the dev, beta, or stable channels. Detected version is ${flutterVersion.frameworkVersion}');
}
// Podspecs use semantic versioning, which don't support hotfixes.
// Fake out a semantic version with major.minor.(patch * 100) + hotfix.
// A real increasing version is required to prompt CocoaPods to fetch
// new artifacts when the source URL changes.
final int minorHotfixVersion = (gitTagVersion.z ?? 0) * 100 + (gitTagVersion.hotfix ?? 0);
final File license = cache.getLicenseFile();
if (!license.existsSync()) {
throwToolExit('Could not find license at ${license.path}');
}
final String licenseSource = license.readAsStringSync();
final String artifactsMode = mode == BuildMode.debug ? 'darwin-x64' : 'darwin-x64-${mode.name}';
final String podspecContents = '''
Pod::Spec.new do |s|
s.name = 'FlutterMacOS'
s.version = '${gitTagVersion.x}.${gitTagVersion.y}.$minorHotfixVersion' # ${flutterVersion.frameworkVersion}
s.summary = 'A UI toolkit for beautiful and fast apps.'
s.description = <<-DESC
Flutter is Google's UI toolkit for building beautiful, fast apps for mobile, web, desktop, and embedded devices from a single codebase.
This pod vends the macOS Flutter engine framework. It is compatible with application frameworks created with this version of the engine and tools.
The pod version matches Flutter version major.minor.(patch * 100) + hotfix.
DESC
s.homepage = 'https://flutter.dev'
s.license = { :type => 'BSD', :text => <<-LICENSE
$licenseSource
LICENSE
}
s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' }
s.source = { :http => '${cache.storageBaseUrl}/flutter_infra_release/flutter/${cache.engineRevision}/$artifactsMode/artifacts.zip' }
s.documentation_url = 'https://flutter.dev/docs'
s.osx.deployment_target = '10.13'
s.vendored_frameworks = 'FlutterMacOS.framework'
s.prepare_command = 'unzip FlutterMacOS.framework -d FlutterMacOS.framework'
end
''';
final File podspec = modeDirectory.childFile('FlutterMacOS.podspec')..createSync(recursive: true);
podspec.writeAsStringSync(podspecContents);
} finally {
status.stop();
}
}
Future<void> _produceAppFramework(
BuildInfo buildInfo,
Directory outputBuildDirectory,
) async {
final Status status = globals.logger.startProgress(
' ├─Building App.xcframework and FlutterMacOS.xcframework...',
);
try {
final Environment environment = Environment(
projectDir: globals.fs.currentDirectory,
outputDir: outputBuildDirectory,
buildDir: project.dartTool.childDirectory('flutter_build'),
cacheDir: globals.cache.getRoot(),
flutterRootDir: globals.fs.directory(Cache.flutterRoot),
defines: <String, String>{
kTargetFile: targetFile,
kTargetPlatform: getNameForTargetPlatform(TargetPlatform.darwin),
kDarwinArchs: defaultMacOSArchsForEnvironment(globals.artifacts!)
.map(getNameForDarwinArch)
.join(' '),
...buildInfo.toBuildSystemEnvironment(),
},
artifacts: globals.artifacts!,
fileSystem: globals.fs,
logger: globals.logger,
processManager: globals.processManager,
platform: globals.platform,
usage: globals.flutterUsage,
engineVersion: globals.artifacts!.isLocalEngine ? null : globals.flutterVersion.engineRevision,
generateDartPluginRegistry: true,
);
Target target;
// Always build debug for simulator.
if (buildInfo.isDebug) {
target = const DebugMacOSBundleFlutterAssets();
} else if (buildInfo.isProfile) {
target = const ProfileMacOSBundleFlutterAssets();
} else {
target = const ReleaseMacOSBundleFlutterAssets();
}
final BuildResult result = await buildSystem.build(target, environment);
if (!result.success) {
for (final ExceptionMeasurement measurement in result.exceptions.values) {
globals.printError(measurement.exception.toString());
}
throwToolExit('The App.xcframework build failed.');
}
} finally {
status.stop();
}
final Directory appFramework = outputBuildDirectory.childDirectory('App.framework');
await BuildFrameworkCommand.produceXCFramework(
<Directory>[appFramework],
'App',
outputBuildDirectory,
globals.processManager,
);
appFramework.deleteSync(recursive: true);
final Directory flutterFramework = outputBuildDirectory.childDirectory('FlutterMacOS.framework');
// If FlutterMacOS.podspec was generated, do not generate XCFramework.
if (!(boolArg('cocoapods') ?? false)) {
await BuildFrameworkCommand.produceXCFramework(
<Directory>[flutterFramework],
'FlutterMacOS',
outputBuildDirectory,
globals.processManager,
);
}
flutterFramework.deleteSync(recursive: true);
}
Future<void> _producePlugins(
String xcodeBuildConfiguration,
Directory buildOutput,
Directory modeDirectory,
) async {
final Status status = globals.logger.startProgress(' ├─Building plugins...');
try {
final List<String> pluginsBuildCommand = <String>[
...globals.xcode!.xcrunCommand(),
'xcodebuild',
'-alltargets',
'-sdk',
'macosx',
'-configuration',
xcodeBuildConfiguration,
'SYMROOT=${buildOutput.path}',
'ONLY_ACTIVE_ARCH=NO', // No device targeted, so build all valid architectures.
'BUILD_LIBRARY_FOR_DISTRIBUTION=YES',
if (boolArg('static') ?? false) 'MACH_O_TYPE=staticlib',
];
final RunResult buildPluginsResult = await globals.processUtils.run(
pluginsBuildCommand,
workingDirectory: project.macos.hostAppRoot.childDirectory('Pods').path,
);
if (buildPluginsResult.exitCode != 0) {
throwToolExit('Unable to build plugin frameworks: ${buildPluginsResult.stderr}');
}
final Directory buildConfiguration = buildOutput.childDirectory(xcodeBuildConfiguration);
final Iterable<Directory> products = buildConfiguration.listSync(followLinks: false).whereType<Directory>();
for (final Directory builtProduct in products) {
for (final FileSystemEntity podProduct in builtProduct.listSync(followLinks: false)) {
final String podFrameworkName = podProduct.basename;
if (globals.fs.path.extension(podFrameworkName) != '.framework') {
continue;
}
final String binaryName = globals.fs.path.basenameWithoutExtension(podFrameworkName);
await BuildFrameworkCommand.produceXCFramework(
<Directory>[
podProduct as Directory,
],
binaryName,
modeDirectory,
globals.processManager,
);
}
}
} finally {
status.stop();
}
}
}