Native assets support for MacOS and iOS (#130494)
Support for FFI calls with `@Native external` functions through Native assets on MacOS and iOS. This enables bundling native code without any build-system boilerplate code. For more info see: * https://github.com/flutter/flutter/issues/129757 ### Implementation details for MacOS and iOS. Dylibs are bundled by (1) making them fat binaries if multiple architectures are targeted, (2) code signing these, and (3) copying them to the frameworks folder. These steps are done manual rather than via CocoaPods. CocoaPods would have done the same steps, but (a) needs the dylibs to be there before the `xcodebuild` invocation (we could trick it, by having a minimal dylib in the place and replace it during the build process, that works), and (b) can't deal with having no dylibs to be bundled (we'd have to bundle a dummy dylib or include some dummy C code in the build file). The dylibs are build as a new target inside flutter assemble, as that is the moment we know what build-mode and architecture to target. The mapping from asset id to dylib-path is passed in to every kernel compilation path. The interesting case is hot-restart where the initial kernel file is compiled by the "inner" flutter assemble, while after hot restart the "outer" flutter run compiled kernel file is pushed to the device. Both kernel files need to contain the mapping. The "inner" flutter assemble gets its mapping from the NativeAssets target which builds the native assets. The "outer" flutter run get its mapping from a dry-run invocation. Since this hot restart can be used for multiple target devices (`flutter run -d all`) it contains the mapping for all known targets. ### Example vs template The PR includes a new template that uses the new native assets in a package and has an app importing that. Separate discussion in: https://github.com/flutter/flutter/issues/131209. ### Tests This PR adds new tests to cover the various use cases. * dev/devicelab/bin/tasks/native_assets_ios.dart * Runs an example app with native assets in all build modes, doing hot reload and hot restart in debug mode. * dev/devicelab/bin/tasks/native_assets_ios_simulator.dart * Runs an example app with native assets, doing hot reload and hot restart. * packages/flutter_tools/test/integration.shard/native_assets_test.dart * Runs (incl hot reload/hot restart), builds, builds frameworks for iOS, MacOS and flutter-tester. * packages/flutter_tools/test/general.shard/build_system/targets/native_assets_test.dart * Unit tests the new Target in the backend. * packages/flutter_tools/test/general.shard/ios/native_assets_test.dart * packages/flutter_tools/test/general.shard/macos/native_assets_test.dart * Unit tests the native assets being packaged on a iOS/MacOS build. It also extends various existing tests: * dev/devicelab/bin/tasks/module_test_ios.dart * Exercises the add2app scenario. * packages/flutter_tools/test/general.shard/features_test.dart * Unit test the new feature flag.
This commit is contained in:
@@ -777,6 +777,8 @@ TargetPlatform getTargetPlatformForName(String platform) {
|
||||
return TargetPlatform.windows_x64;
|
||||
case 'web-javascript':
|
||||
return TargetPlatform.web_javascript;
|
||||
case 'flutter-tester':
|
||||
return TargetPlatform.tester;
|
||||
}
|
||||
throw Exception('Unsupported platform name "$platform"');
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:package_config/package_config.dart';
|
||||
|
||||
import '../../artifacts.dart';
|
||||
import '../../base/build.dart';
|
||||
import '../../base/common.dart';
|
||||
import '../../base/file_system.dart';
|
||||
import '../../base/io.dart';
|
||||
import '../../build_info.dart';
|
||||
@@ -19,6 +20,7 @@ import 'assets.dart';
|
||||
import 'dart_plugin_registrant.dart';
|
||||
import 'icon_tree_shaker.dart';
|
||||
import 'localizations.dart';
|
||||
import 'native_assets.dart';
|
||||
import 'shader_compiler.dart';
|
||||
|
||||
/// Copies the pre-built flutter bundle.
|
||||
@@ -125,6 +127,7 @@ class KernelSnapshot extends Target {
|
||||
|
||||
@override
|
||||
List<Source> get inputs => const <Source>[
|
||||
Source.pattern('{BUILD_DIR}/native_assets.yaml'),
|
||||
Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
|
||||
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/common.dart'),
|
||||
Source.artifact(Artifact.platformKernelDill),
|
||||
@@ -142,6 +145,7 @@ class KernelSnapshot extends Target {
|
||||
|
||||
@override
|
||||
List<Target> get dependencies => const <Target>[
|
||||
NativeAssets(),
|
||||
GenerateLocalizationsTarget(),
|
||||
DartPluginRegistrantTarget(),
|
||||
];
|
||||
@@ -178,6 +182,13 @@ class KernelSnapshot extends Target {
|
||||
final List<String>? fileSystemRoots = environment.defines[kFileSystemRoots]?.split(',');
|
||||
final String? fileSystemScheme = environment.defines[kFileSystemScheme];
|
||||
|
||||
final File nativeAssetsFile = environment.buildDir.childFile('native_assets.yaml');
|
||||
final String nativeAssets = nativeAssetsFile.path;
|
||||
if (!await nativeAssetsFile.exists()) {
|
||||
throwToolExit("$nativeAssets doesn't exist.");
|
||||
}
|
||||
environment.logger.printTrace('Embedding native assets mapping $nativeAssets in kernel.');
|
||||
|
||||
TargetModel targetModel = TargetModel.flutter;
|
||||
if (targetPlatform == TargetPlatform.fuchsia_x64 ||
|
||||
targetPlatform == TargetPlatform.fuchsia_arm64) {
|
||||
@@ -251,6 +262,7 @@ class KernelSnapshot extends Target {
|
||||
buildDir: environment.buildDir,
|
||||
targetOS: targetOS,
|
||||
checkDartPluginRegistry: environment.generateDartPluginRegistry,
|
||||
nativeAssets: nativeAssets,
|
||||
);
|
||||
if (output == null || output.errorCount != 0) {
|
||||
throw Exception();
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// 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 'package:native_assets_cli/native_assets_cli.dart' show Asset;
|
||||
|
||||
import '../../base/common.dart';
|
||||
import '../../base/file_system.dart';
|
||||
import '../../base/platform.dart';
|
||||
import '../../build_info.dart';
|
||||
import '../../ios/native_assets.dart';
|
||||
import '../../macos/native_assets.dart';
|
||||
import '../../macos/xcode.dart';
|
||||
import '../../native_assets.dart';
|
||||
import '../build_system.dart';
|
||||
import '../depfile.dart';
|
||||
import '../exceptions.dart';
|
||||
import 'common.dart';
|
||||
|
||||
/// Builds the right native assets for a Flutter app.
|
||||
///
|
||||
/// The build mode and target architecture can be changed from the
|
||||
/// native build project (Xcode etc.), so only `flutter assemble` has the
|
||||
/// information about build-mode and target architecture.
|
||||
/// Invocations of flutter_tools other than `flutter assemble` are dry runs.
|
||||
///
|
||||
/// This step needs to be consistent with the dry run invocations in `flutter
|
||||
/// run`s so that the kernel mapping of asset id to dylib lines up after hot
|
||||
/// restart.
|
||||
///
|
||||
/// [KernelSnapshot] depends on this target. We produce a native_assets.yaml
|
||||
/// here, and embed that mapping inside the kernel snapshot.
|
||||
///
|
||||
/// The build always produces a valid native_assets.yaml and a native_assets.d
|
||||
/// even if there are no native assets. This way the caching logic won't try to
|
||||
/// rebuild.
|
||||
class NativeAssets extends Target {
|
||||
const NativeAssets({
|
||||
@visibleForTesting NativeAssetsBuildRunner? buildRunner,
|
||||
}) : _buildRunner = buildRunner;
|
||||
|
||||
final NativeAssetsBuildRunner? _buildRunner;
|
||||
|
||||
@override
|
||||
Future<void> build(Environment environment) async {
|
||||
final String? targetPlatformEnvironment = environment.defines[kTargetPlatform];
|
||||
if (targetPlatformEnvironment == null) {
|
||||
throw MissingDefineException(kTargetPlatform, name);
|
||||
}
|
||||
final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment);
|
||||
|
||||
final Uri projectUri = environment.projectDir.uri;
|
||||
final FileSystem fileSystem = environment.fileSystem;
|
||||
final NativeAssetsBuildRunner buildRunner = _buildRunner ?? NativeAssetsBuildRunnerImpl(projectUri, fileSystem, environment.logger);
|
||||
|
||||
final List<Uri> dependencies;
|
||||
switch (targetPlatform) {
|
||||
case TargetPlatform.ios:
|
||||
final String? iosArchsEnvironment = environment.defines[kIosArchs];
|
||||
if (iosArchsEnvironment == null) {
|
||||
throw MissingDefineException(kIosArchs, name);
|
||||
}
|
||||
final List<DarwinArch> iosArchs = iosArchsEnvironment.split(' ').map(getDarwinArchForName).toList();
|
||||
final String? environmentBuildMode = environment.defines[kBuildMode];
|
||||
if (environmentBuildMode == null) {
|
||||
throw MissingDefineException(kBuildMode, name);
|
||||
}
|
||||
final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode);
|
||||
final String? sdkRoot = environment.defines[kSdkRoot];
|
||||
if (sdkRoot == null) {
|
||||
throw MissingDefineException(kSdkRoot, name);
|
||||
}
|
||||
final EnvironmentType environmentType = environmentTypeFromSdkroot(sdkRoot, environment.fileSystem)!;
|
||||
dependencies = await buildNativeAssetsIOS(
|
||||
environmentType: environmentType,
|
||||
darwinArchs: iosArchs,
|
||||
buildMode: buildMode,
|
||||
projectUri: projectUri,
|
||||
codesignIdentity: environment.defines[kCodesignIdentity],
|
||||
fileSystem: fileSystem,
|
||||
buildRunner: buildRunner,
|
||||
yamlParentDirectory: environment.buildDir.uri,
|
||||
);
|
||||
case TargetPlatform.darwin:
|
||||
final String? darwinArchsEnvironment = environment.defines[kDarwinArchs];
|
||||
if (darwinArchsEnvironment == null) {
|
||||
throw MissingDefineException(kDarwinArchs, name);
|
||||
}
|
||||
final List<DarwinArch> darwinArchs = darwinArchsEnvironment.split(' ').map(getDarwinArchForName).toList();
|
||||
final String? environmentBuildMode = environment.defines[kBuildMode];
|
||||
if (environmentBuildMode == null) {
|
||||
throw MissingDefineException(kBuildMode, name);
|
||||
}
|
||||
final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode);
|
||||
(_, dependencies) = await buildNativeAssetsMacOS(
|
||||
darwinArchs: darwinArchs,
|
||||
buildMode: buildMode,
|
||||
projectUri: projectUri,
|
||||
codesignIdentity: environment.defines[kCodesignIdentity],
|
||||
yamlParentDirectory: environment.buildDir.uri,
|
||||
fileSystem: fileSystem,
|
||||
buildRunner: buildRunner,
|
||||
);
|
||||
case TargetPlatform.tester:
|
||||
if (const LocalPlatform().isMacOS) {
|
||||
(_, dependencies) = await buildNativeAssetsMacOS(
|
||||
buildMode: BuildMode.debug,
|
||||
projectUri: projectUri,
|
||||
codesignIdentity: environment.defines[kCodesignIdentity],
|
||||
yamlParentDirectory: environment.buildDir.uri,
|
||||
fileSystem: fileSystem,
|
||||
buildRunner: buildRunner,
|
||||
flutterTester: true,
|
||||
);
|
||||
} else {
|
||||
// TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757
|
||||
// Write the file we claim to have in the [outputs].
|
||||
await writeNativeAssetsYaml(<Asset>[], environment.buildDir.uri, fileSystem);
|
||||
dependencies = <Uri>[];
|
||||
}
|
||||
case TargetPlatform.android_arm:
|
||||
case TargetPlatform.android_arm64:
|
||||
case TargetPlatform.android_x64:
|
||||
case TargetPlatform.android_x86:
|
||||
case TargetPlatform.android:
|
||||
case TargetPlatform.fuchsia_arm64:
|
||||
case TargetPlatform.fuchsia_x64:
|
||||
case TargetPlatform.linux_arm64:
|
||||
case TargetPlatform.linux_x64:
|
||||
case TargetPlatform.web_javascript:
|
||||
case TargetPlatform.windows_x64:
|
||||
// TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757
|
||||
// Write the file we claim to have in the [outputs].
|
||||
await writeNativeAssetsYaml(<Asset>[], environment.buildDir.uri, fileSystem);
|
||||
dependencies = <Uri>[];
|
||||
}
|
||||
|
||||
final File nativeAssetsFile = environment.buildDir.childFile('native_assets.yaml');
|
||||
final Depfile depfile = Depfile(
|
||||
<File>[
|
||||
for (final Uri dependency in dependencies) fileSystem.file(dependency),
|
||||
],
|
||||
<File>[
|
||||
nativeAssetsFile,
|
||||
],
|
||||
);
|
||||
final File outputDepfile = environment.buildDir.childFile('native_assets.d');
|
||||
if (!outputDepfile.parent.existsSync()) {
|
||||
outputDepfile.parent.createSync(recursive: true);
|
||||
}
|
||||
environment.depFileService.writeToFile(depfile, outputDepfile);
|
||||
if (!await nativeAssetsFile.exists()) {
|
||||
throwToolExit("${nativeAssetsFile.path} doesn't exist.");
|
||||
}
|
||||
if (!await outputDepfile.exists()) {
|
||||
throwToolExit("${outputDepfile.path} doesn't exist.");
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
List<String> get depfiles => <String>[
|
||||
'native_assets.d',
|
||||
];
|
||||
|
||||
@override
|
||||
List<Target> get dependencies => <Target>[];
|
||||
|
||||
@override
|
||||
List<Source> get inputs => const <Source>[
|
||||
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart'),
|
||||
// If different packages are resolved, different native assets might need to be built.
|
||||
Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
|
||||
];
|
||||
|
||||
@override
|
||||
String get name => 'native_assets';
|
||||
|
||||
@override
|
||||
List<Source> get outputs => const <Source>[
|
||||
Source.pattern('{BUILD_DIR}/native_assets.yaml'),
|
||||
];
|
||||
}
|
||||
@@ -270,6 +270,28 @@ class BuildIOSFrameworkCommand extends BuildFrameworkCommand {
|
||||
|
||||
final Status status = globals.logger.startProgress(
|
||||
' └─Moving to ${globals.fs.path.relative(modeDirectory.path)}');
|
||||
|
||||
// Copy the native assets. The native assets have already been signed in
|
||||
// buildNativeAssetsMacOS.
|
||||
final Directory nativeAssetsDirectory = globals.fs
|
||||
.directory(getBuildDirectory())
|
||||
.childDirectory('native_assets/ios/');
|
||||
if (await nativeAssetsDirectory.exists()) {
|
||||
final ProcessResult rsyncResult = await globals.processManager.run(<Object>[
|
||||
'rsync',
|
||||
'-av',
|
||||
'--filter',
|
||||
'- .DS_Store',
|
||||
'--filter',
|
||||
'- native_assets.yaml',
|
||||
nativeAssetsDirectory.path,
|
||||
modeDirectory.path,
|
||||
]);
|
||||
if (rsyncResult.exitCode != 0) {
|
||||
throwToolExit('Failed to copy native assets:\n${rsyncResult.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Delete the intermediaries since they would have been copied into our
|
||||
// output frameworks.
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:meta/meta.dart';
|
||||
|
||||
import '../base/common.dart';
|
||||
import '../base/file_system.dart';
|
||||
import '../base/io.dart';
|
||||
import '../base/logger.dart';
|
||||
import '../base/process.dart';
|
||||
import '../base/utils.dart';
|
||||
@@ -96,6 +97,26 @@ class BuildMacOSFrameworkCommand extends BuildFrameworkCommand {
|
||||
|
||||
globals.logger.printStatus(' └─Moving to ${globals.fs.path.relative(modeDirectory.path)}');
|
||||
|
||||
// Copy the native assets.
|
||||
final Directory nativeAssetsDirectory = globals.fs
|
||||
.directory(getBuildDirectory())
|
||||
.childDirectory('native_assets/macos/');
|
||||
if (await nativeAssetsDirectory.exists()) {
|
||||
final ProcessResult rsyncResult = await globals.processManager.run(<Object>[
|
||||
'rsync',
|
||||
'-av',
|
||||
'--filter',
|
||||
'- .DS_Store',
|
||||
'--filter',
|
||||
'- native_assets.yaml',
|
||||
nativeAssetsDirectory.path,
|
||||
modeDirectory.path,
|
||||
]);
|
||||
if (rsyncResult.exitCode != 0) {
|
||||
throwToolExit('Failed to copy native assets:\n${rsyncResult.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the intermediaries since they would have been copied into our
|
||||
// output frameworks.
|
||||
if (buildOutput.existsSync()) {
|
||||
|
||||
@@ -36,10 +36,11 @@ class CreateCommand extends CreateBase {
|
||||
argParser.addOption(
|
||||
'template',
|
||||
abbr: 't',
|
||||
allowed: FlutterProjectType.values.map<String>((FlutterProjectType e) => e.cliName),
|
||||
allowed: FlutterProjectType.enabledValues
|
||||
.map<String>((FlutterProjectType e) => e.cliName),
|
||||
help: 'Specify the type of project to create.',
|
||||
valueHelp: 'type',
|
||||
allowedHelp: CliEnum.allowedHelp(FlutterProjectType.values),
|
||||
allowedHelp: CliEnum.allowedHelp(FlutterProjectType.enabledValues),
|
||||
);
|
||||
argParser.addOption(
|
||||
'sample',
|
||||
@@ -206,12 +207,14 @@ class CreateCommand extends CreateBase {
|
||||
final FlutterProjectType template = _getProjectType(projectDir);
|
||||
final bool generateModule = template == FlutterProjectType.module;
|
||||
final bool generateMethodChannelsPlugin = template == FlutterProjectType.plugin;
|
||||
final bool generateFfiPackage = template == FlutterProjectType.packageFfi;
|
||||
final bool generateFfiPlugin = template == FlutterProjectType.pluginFfi;
|
||||
final bool generateFfi = generateFfiPlugin || generateFfiPackage;
|
||||
final bool generatePackage = template == FlutterProjectType.package;
|
||||
|
||||
final List<String> platforms = stringsArg('platforms');
|
||||
// `--platforms` does not support module or package.
|
||||
if (argResults!.wasParsed('platforms') && (generateModule || generatePackage)) {
|
||||
if (argResults!.wasParsed('platforms') && (generateModule || generatePackage || generateFfiPackage)) {
|
||||
final String template = generateModule ? 'module' : 'package';
|
||||
throwToolExit(
|
||||
'The "--platforms" argument is not supported in $template template.',
|
||||
@@ -225,15 +228,15 @@ class CreateCommand extends CreateBase {
|
||||
'The web platform is not supported in plugin_ffi template.',
|
||||
exitCode: 2,
|
||||
);
|
||||
} else if (generateFfiPlugin && argResults!.wasParsed('ios-language')) {
|
||||
} else if (generateFfi && argResults!.wasParsed('ios-language')) {
|
||||
throwToolExit(
|
||||
'The "ios-language" option is not supported with the plugin_ffi '
|
||||
'The "ios-language" option is not supported with the ${template.cliName} '
|
||||
'template: the language will always be C or C++.',
|
||||
exitCode: 2,
|
||||
);
|
||||
} else if (generateFfiPlugin && argResults!.wasParsed('android-language')) {
|
||||
} else if (generateFfi && argResults!.wasParsed('android-language')) {
|
||||
throwToolExit(
|
||||
'The "android-language" option is not supported with the plugin_ffi '
|
||||
'The "android-language" option is not supported with the ${template.cliName} '
|
||||
'template: the language will always be C or C++.',
|
||||
exitCode: 2,
|
||||
);
|
||||
@@ -306,6 +309,7 @@ class CreateCommand extends CreateBase {
|
||||
flutterRoot: flutterRoot,
|
||||
withPlatformChannelPluginHook: generateMethodChannelsPlugin,
|
||||
withFfiPluginHook: generateFfiPlugin,
|
||||
withFfiPackage: generateFfiPackage,
|
||||
withEmptyMain: emptyArgument,
|
||||
androidLanguage: stringArg('android-language'),
|
||||
iosLanguage: stringArg('ios-language'),
|
||||
@@ -393,6 +397,15 @@ class CreateCommand extends CreateBase {
|
||||
projectType: template,
|
||||
);
|
||||
pubContext = PubContext.createPlugin;
|
||||
case FlutterProjectType.packageFfi:
|
||||
generatedFileCount += await _generateFfiPackage(
|
||||
relativeDir,
|
||||
templateContext,
|
||||
overwrite: overwrite,
|
||||
printStatusWhenWriting: !creatingNewProject,
|
||||
projectType: template,
|
||||
);
|
||||
pubContext = PubContext.createPackage;
|
||||
}
|
||||
|
||||
if (boolArg('pub')) {
|
||||
@@ -403,14 +416,21 @@ class CreateCommand extends CreateBase {
|
||||
offline: boolArg('offline'),
|
||||
outputMode: PubOutputMode.summaryOnly,
|
||||
);
|
||||
await project.ensureReadyForPlatformSpecificTooling(
|
||||
androidPlatform: includeAndroid,
|
||||
iosPlatform: includeIos,
|
||||
linuxPlatform: includeLinux,
|
||||
macOSPlatform: includeMacos,
|
||||
windowsPlatform: includeWindows,
|
||||
webPlatform: includeWeb,
|
||||
);
|
||||
// Setting `includeIos` etc to false as with FlutterProjectType.package
|
||||
// causes the example sub directory to not get os sub directories.
|
||||
// This will lead to `flutter build ios` to fail in the example.
|
||||
// TODO(dacoharkes): Uncouple the app and parent project platforms. https://github.com/flutter/flutter/issues/133874
|
||||
// Then this if can be removed.
|
||||
if (!generateFfiPackage) {
|
||||
await project.ensureReadyForPlatformSpecificTooling(
|
||||
androidPlatform: includeAndroid,
|
||||
iosPlatform: includeIos,
|
||||
linuxPlatform: includeLinux,
|
||||
macOSPlatform: includeMacos,
|
||||
windowsPlatform: includeWindows,
|
||||
webPlatform: includeWeb,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (sampleCode != null) {
|
||||
_applySample(relativeDir, sampleCode);
|
||||
@@ -663,6 +683,48 @@ Your $application code is in $relativeAppMain.
|
||||
return generatedCount;
|
||||
}
|
||||
|
||||
Future<int> _generateFfiPackage(
|
||||
Directory directory,
|
||||
Map<String, Object?> templateContext, {
|
||||
bool overwrite = false,
|
||||
bool printStatusWhenWriting = true,
|
||||
required FlutterProjectType projectType,
|
||||
}) async {
|
||||
int generatedCount = 0;
|
||||
final String? description = argResults!.wasParsed('description')
|
||||
? stringArg('description')
|
||||
: 'A new Dart FFI package project.';
|
||||
templateContext['description'] = description;
|
||||
generatedCount += await renderMerged(
|
||||
<String>[
|
||||
'package_ffi',
|
||||
],
|
||||
directory,
|
||||
templateContext,
|
||||
overwrite: overwrite,
|
||||
printStatusWhenWriting: printStatusWhenWriting,
|
||||
);
|
||||
|
||||
final FlutterProject project = FlutterProject.fromDirectory(directory);
|
||||
|
||||
final String? projectName = templateContext['projectName'] as String?;
|
||||
final String exampleProjectName = '${projectName}_example';
|
||||
templateContext['projectName'] = exampleProjectName;
|
||||
templateContext['description'] = 'Demonstrates how to use the $projectName package.';
|
||||
templateContext['pluginProjectName'] = projectName;
|
||||
|
||||
generatedCount += await generateApp(
|
||||
<String>['app'],
|
||||
project.example.directory,
|
||||
templateContext,
|
||||
overwrite: overwrite,
|
||||
pluginExampleApp: true,
|
||||
printStatusWhenWriting: printStatusWhenWriting,
|
||||
projectType: projectType,
|
||||
);
|
||||
return generatedCount;
|
||||
}
|
||||
|
||||
// Takes an application template and replaces the main.dart with one from the
|
||||
// documentation website in sampleCode. Returns the difference in the number
|
||||
// of files after applying the sample, since it also deletes the application's
|
||||
|
||||
@@ -352,6 +352,7 @@ abstract class CreateBase extends FlutterCommand {
|
||||
String? gradleVersion,
|
||||
bool withPlatformChannelPluginHook = false,
|
||||
bool withFfiPluginHook = false,
|
||||
bool withFfiPackage = false,
|
||||
bool withEmptyMain = false,
|
||||
bool ios = false,
|
||||
bool android = false,
|
||||
@@ -399,9 +400,11 @@ abstract class CreateBase extends FlutterCommand {
|
||||
'pluginClassCapitalSnakeCase': pluginClassCapitalSnakeCase,
|
||||
'pluginDartClass': pluginDartClass,
|
||||
'pluginProjectUUID': const Uuid().v4().toUpperCase(),
|
||||
'withFfi': withFfiPluginHook || withFfiPackage,
|
||||
'withFfiPackage': withFfiPackage,
|
||||
'withFfiPluginHook': withFfiPluginHook,
|
||||
'withPlatformChannelPluginHook': withPlatformChannelPluginHook,
|
||||
'withPluginHook': withFfiPluginHook || withPlatformChannelPluginHook,
|
||||
'withPluginHook': withFfiPluginHook || withFfiPackage || withPlatformChannelPluginHook,
|
||||
'withEmptyMain': withEmptyMain,
|
||||
'androidLanguage': androidLanguage,
|
||||
'iosLanguage': iosLanguage,
|
||||
|
||||
@@ -240,6 +240,7 @@ class KernelCompiler {
|
||||
required bool trackWidgetCreation,
|
||||
required List<String> dartDefines,
|
||||
required PackageConfig packageConfig,
|
||||
String? nativeAssets,
|
||||
}) async {
|
||||
final TargetPlatform? platform = targetModel == TargetModel.dartdevc ? TargetPlatform.web_javascript : null;
|
||||
final String frontendServer = _artifacts.getArtifactPath(
|
||||
@@ -337,6 +338,10 @@ class KernelCompiler {
|
||||
'package:flutter/src/dart_plugin_registrant.dart',
|
||||
'-Dflutter.dart_plugin_registrant=$dartPluginRegistrantUri',
|
||||
],
|
||||
if (nativeAssets != null) ...<String>[
|
||||
'--native-assets',
|
||||
nativeAssets,
|
||||
],
|
||||
// See: https://github.com/flutter/flutter/issues/103994
|
||||
'--verbosity=error',
|
||||
...?extraFrontEndOptions,
|
||||
@@ -381,9 +386,10 @@ class _RecompileRequest extends _CompilationRequest {
|
||||
this.invalidatedFiles,
|
||||
this.outputPath,
|
||||
this.packageConfig,
|
||||
this.suppressErrors,
|
||||
{this.additionalSourceUri}
|
||||
);
|
||||
this.suppressErrors, {
|
||||
this.additionalSourceUri,
|
||||
this.nativeAssetsYamlUri,
|
||||
});
|
||||
|
||||
Uri mainUri;
|
||||
List<Uri>? invalidatedFiles;
|
||||
@@ -391,6 +397,7 @@ class _RecompileRequest extends _CompilationRequest {
|
||||
PackageConfig packageConfig;
|
||||
bool suppressErrors;
|
||||
final Uri? additionalSourceUri;
|
||||
final Uri? nativeAssetsYamlUri;
|
||||
|
||||
@override
|
||||
Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async =>
|
||||
@@ -515,6 +522,7 @@ abstract class ResidentCompiler {
|
||||
bool suppressErrors = false,
|
||||
bool checkDartPluginRegistry = false,
|
||||
File? dartPluginRegistrant,
|
||||
Uri? nativeAssetsYaml,
|
||||
});
|
||||
|
||||
Future<CompilerOutput?> compileExpression(
|
||||
@@ -663,6 +671,7 @@ class DefaultResidentCompiler implements ResidentCompiler {
|
||||
File? dartPluginRegistrant,
|
||||
String? projectRootPath,
|
||||
FileSystem? fs,
|
||||
Uri? nativeAssetsYaml,
|
||||
}) async {
|
||||
if (!_controller.hasListener) {
|
||||
_controller.stream.listen(_handleCompilationRequest);
|
||||
@@ -681,6 +690,7 @@ class DefaultResidentCompiler implements ResidentCompiler {
|
||||
packageConfig,
|
||||
suppressErrors,
|
||||
additionalSourceUri: additionalSourceUri,
|
||||
nativeAssetsYamlUri: nativeAssetsYaml,
|
||||
));
|
||||
return completer.future;
|
||||
}
|
||||
@@ -699,12 +709,22 @@ class DefaultResidentCompiler implements ResidentCompiler {
|
||||
toMultiRootPath(request.additionalSourceUri!, fileSystemScheme, fileSystemRoots, _platform.isWindows);
|
||||
}
|
||||
|
||||
final String? nativeAssets = request.nativeAssetsYamlUri?.toString();
|
||||
final Process? server = _server;
|
||||
if (server == null) {
|
||||
return _compile(mainUri, request.outputPath, additionalSourceUri: additionalSourceUri);
|
||||
return _compile(
|
||||
mainUri,
|
||||
request.outputPath,
|
||||
additionalSourceUri: additionalSourceUri,
|
||||
nativeAssetsUri: nativeAssets,
|
||||
);
|
||||
}
|
||||
final String inputKey = Uuid().generateV4();
|
||||
|
||||
if (nativeAssets != null && nativeAssets.isNotEmpty) {
|
||||
server.stdin.writeln('native-assets $nativeAssets');
|
||||
_logger.printTrace('<- native-assets $nativeAssets');
|
||||
}
|
||||
server.stdin.writeln('recompile $mainUri $inputKey');
|
||||
_logger.printTrace('<- recompile $mainUri $inputKey');
|
||||
final List<Uri>? invalidatedFiles = request.invalidatedFiles;
|
||||
@@ -746,9 +766,10 @@ class DefaultResidentCompiler implements ResidentCompiler {
|
||||
|
||||
Future<CompilerOutput?> _compile(
|
||||
String scriptUri,
|
||||
String? outputPath,
|
||||
{String? additionalSourceUri}
|
||||
) async {
|
||||
String? outputPath, {
|
||||
String? additionalSourceUri,
|
||||
String? nativeAssetsUri,
|
||||
}) async {
|
||||
final TargetPlatform? platform = (targetModel == TargetModel.dartdevc) ? TargetPlatform.web_javascript : null;
|
||||
final String frontendServer = artifacts.getArtifactPath(
|
||||
Artifact.frontendServerSnapshotForEngineDartSdk,
|
||||
@@ -806,6 +827,10 @@ class DefaultResidentCompiler implements ResidentCompiler {
|
||||
'package:flutter/src/dart_plugin_registrant.dart',
|
||||
'-Dflutter.dart_plugin_registrant=$additionalSourceUri',
|
||||
],
|
||||
if (nativeAssetsUri != null) ...<String>[
|
||||
'--native-assets',
|
||||
nativeAssetsUri,
|
||||
],
|
||||
if (platformDill != null) ...<String>[
|
||||
'--platform',
|
||||
platformDill!,
|
||||
@@ -842,6 +867,11 @@ class DefaultResidentCompiler implements ResidentCompiler {
|
||||
}
|
||||
}));
|
||||
|
||||
if (nativeAssetsUri != null && nativeAssetsUri.isNotEmpty) {
|
||||
_server?.stdin.writeln('native-assets $nativeAssetsUri');
|
||||
_logger.printTrace('<- native-assets $nativeAssetsUri');
|
||||
}
|
||||
|
||||
_server?.stdin.writeln('compile $scriptUri');
|
||||
_logger.printTrace('<- compile $scriptUri');
|
||||
|
||||
|
||||
@@ -50,6 +50,9 @@ abstract class FeatureFlags {
|
||||
/// Whether animations are used in the command line interface.
|
||||
bool get isCliAnimationEnabled => true;
|
||||
|
||||
/// Whether native assets compilation and bundling is enabled.
|
||||
bool get isNativeAssetsEnabled => false;
|
||||
|
||||
/// Whether a particular feature is enabled for the current channel.
|
||||
///
|
||||
/// Prefer using one of the specific getters above instead of this API.
|
||||
@@ -68,6 +71,7 @@ const List<Feature> allFeatures = <Feature>[
|
||||
flutterCustomDevicesFeature,
|
||||
flutterWebWasm,
|
||||
cliAnimation,
|
||||
nativeAssets,
|
||||
];
|
||||
|
||||
/// All current Flutter feature flags that can be configured.
|
||||
@@ -158,6 +162,16 @@ const Feature cliAnimation = Feature.fullyEnabled(
|
||||
configSetting: 'cli-animations',
|
||||
);
|
||||
|
||||
/// Enable native assets compilation and bundling.
|
||||
const Feature nativeAssets = Feature(
|
||||
name: 'native assets compilation and bundling',
|
||||
configSetting: 'enable-native-assets',
|
||||
environmentOverride: 'FLUTTER_NATIVE_ASSETS',
|
||||
master: FeatureChannelSetting(
|
||||
available: true,
|
||||
),
|
||||
);
|
||||
|
||||
/// A [Feature] is a process for conditionally enabling tool features.
|
||||
///
|
||||
/// All settings are optional, and if not provided will generally default to
|
||||
|
||||
@@ -87,7 +87,6 @@ class FlutterDeviceManager extends DeviceManager {
|
||||
processManager: processManager,
|
||||
logger: logger,
|
||||
artifacts: artifacts,
|
||||
operatingSystemUtils: operatingSystemUtils,
|
||||
),
|
||||
MacOSDevices(
|
||||
processManager: processManager,
|
||||
|
||||
@@ -55,6 +55,9 @@ class FlutterFeatureFlags implements FeatureFlags {
|
||||
return isEnabled(cliAnimation);
|
||||
}
|
||||
|
||||
@override
|
||||
bool get isNativeAssetsEnabled => isEnabled(nativeAssets);
|
||||
|
||||
@override
|
||||
bool isEnabled(Feature feature) {
|
||||
final String currentChannel = _flutterVersion.channel;
|
||||
|
||||
@@ -970,7 +970,7 @@ Future<void> _writeWebPluginRegistrant(FlutterProject project, List<Plugin> plug
|
||||
/// be created only if missing.
|
||||
///
|
||||
/// This uses [project.flutterPluginsDependenciesFile], so it should only be
|
||||
/// run after refreshPluginList has been run since the last plugin change.
|
||||
/// run after [refreshPluginsList] has been run since the last plugin change.
|
||||
void createPluginSymlinks(FlutterProject project, {bool force = false, @visibleForTesting FeatureFlags? featureFlagsOverride}) {
|
||||
final FeatureFlags localFeatureFlags = featureFlagsOverride ?? featureFlags;
|
||||
Map<String, Object?>? platformPlugins;
|
||||
|
||||
@@ -7,6 +7,7 @@ import 'package:yaml/yaml.dart';
|
||||
import 'base/file_system.dart';
|
||||
import 'base/logger.dart';
|
||||
import 'base/utils.dart';
|
||||
import 'features.dart';
|
||||
import 'project.dart';
|
||||
import 'template.dart';
|
||||
import 'version.dart';
|
||||
@@ -28,6 +29,9 @@ enum FlutterProjectType implements CliEnum {
|
||||
/// components, only Dart.
|
||||
package,
|
||||
|
||||
/// This is a Dart package project with external builds for native components.
|
||||
packageFfi,
|
||||
|
||||
/// This is a native plugin project.
|
||||
plugin,
|
||||
|
||||
@@ -52,6 +56,10 @@ enum FlutterProjectType implements CliEnum {
|
||||
'Generate a shareable Flutter project containing an API '
|
||||
'in Dart code with a platform-specific implementation through dart:ffi for Android, iOS, '
|
||||
'Linux, macOS, Windows, or any combination of these.',
|
||||
FlutterProjectType.packageFfi =>
|
||||
'Generate a shareable Dart/Flutter project containing an API '
|
||||
'in Dart code with a platform-specific implementation through dart:ffi for Android, iOS, '
|
||||
'Linux, macOS, and Windows.',
|
||||
FlutterProjectType.module =>
|
||||
'Generate a project to add a Flutter module to an existing Android or iOS application.',
|
||||
};
|
||||
@@ -64,6 +72,16 @@ enum FlutterProjectType implements CliEnum {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static List<FlutterProjectType> get enabledValues {
|
||||
return <FlutterProjectType>[
|
||||
for (final FlutterProjectType value in values)
|
||||
if (value == FlutterProjectType.packageFfi) ...<FlutterProjectType>[
|
||||
if (featureFlags.isNativeAssetsEnabled) value
|
||||
] else
|
||||
value,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies the expected yaml keys are present in the file.
|
||||
|
||||
171
packages/flutter_tools/lib/src/ios/native_assets.dart
Normal file
171
packages/flutter_tools/lib/src/ios/native_assets.dart
Normal file
@@ -0,0 +1,171 @@
|
||||
// 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:native_assets_builder/native_assets_builder.dart' show BuildResult;
|
||||
import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode;
|
||||
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
|
||||
|
||||
import '../base/file_system.dart';
|
||||
import '../build_info.dart';
|
||||
import '../globals.dart' as globals;
|
||||
|
||||
import '../macos/native_assets_host.dart';
|
||||
import '../native_assets.dart';
|
||||
|
||||
/// Dry run the native builds.
|
||||
///
|
||||
/// This does not build native assets, it only simulates what the final paths
|
||||
/// of all assets will be so that this can be embedded in the kernel file and
|
||||
/// the Xcode project.
|
||||
Future<Uri?> dryRunNativeAssetsIOS({
|
||||
required NativeAssetsBuildRunner buildRunner,
|
||||
required Uri projectUri,
|
||||
required FileSystem fileSystem,
|
||||
}) async {
|
||||
if (await hasNoPackageConfig(buildRunner) || await isDisabledAndNoNativeAssets(buildRunner)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Uri buildUri_ = nativeAssetsBuildUri(projectUri, OS.iOS);
|
||||
final Iterable<Asset> assetTargetLocations = await dryRunNativeAssetsIOSInternal(
|
||||
fileSystem,
|
||||
projectUri,
|
||||
buildRunner,
|
||||
);
|
||||
final Uri nativeAssetsUri = await writeNativeAssetsYaml(
|
||||
assetTargetLocations,
|
||||
buildUri_,
|
||||
fileSystem,
|
||||
);
|
||||
return nativeAssetsUri;
|
||||
}
|
||||
|
||||
Future<Iterable<Asset>> dryRunNativeAssetsIOSInternal(
|
||||
FileSystem fileSystem,
|
||||
Uri projectUri,
|
||||
NativeAssetsBuildRunner buildRunner,
|
||||
) async {
|
||||
const OS targetOs = OS.iOS;
|
||||
globals.logger.printTrace('Dry running native assets for $targetOs.');
|
||||
final List<Asset> nativeAssets = (await buildRunner.dryRun(
|
||||
linkModePreference: LinkModePreference.dynamic,
|
||||
targetOs: targetOs,
|
||||
workingDirectory: projectUri,
|
||||
includeParentEnvironment: true,
|
||||
))
|
||||
.assets;
|
||||
ensureNoLinkModeStatic(nativeAssets);
|
||||
globals.logger.printTrace('Dry running native assets for $targetOs done.');
|
||||
final Iterable<Asset> assetTargetLocations = _assetTargetLocations(nativeAssets).values;
|
||||
return assetTargetLocations;
|
||||
}
|
||||
|
||||
/// Builds native assets.
|
||||
Future<List<Uri>> buildNativeAssetsIOS({
|
||||
required NativeAssetsBuildRunner buildRunner,
|
||||
required List<DarwinArch> darwinArchs,
|
||||
required EnvironmentType environmentType,
|
||||
required Uri projectUri,
|
||||
required BuildMode buildMode,
|
||||
String? codesignIdentity,
|
||||
required Uri yamlParentDirectory,
|
||||
required FileSystem fileSystem,
|
||||
}) async {
|
||||
if (await hasNoPackageConfig(buildRunner) || await isDisabledAndNoNativeAssets(buildRunner)) {
|
||||
await writeNativeAssetsYaml(<Asset>[], yamlParentDirectory, fileSystem);
|
||||
return <Uri>[];
|
||||
}
|
||||
|
||||
final List<Target> targets = darwinArchs.map(_getNativeTarget).toList();
|
||||
final native_assets_cli.BuildMode buildModeCli = nativeAssetsBuildMode(buildMode);
|
||||
|
||||
const OS targetOs = OS.iOS;
|
||||
final Uri buildUri_ = nativeAssetsBuildUri(projectUri, targetOs);
|
||||
final IOSSdk iosSdk = _getIOSSdk(environmentType);
|
||||
|
||||
globals.logger.printTrace('Building native assets for $targets $buildModeCli.');
|
||||
final List<Asset> nativeAssets = <Asset>[];
|
||||
final Set<Uri> dependencies = <Uri>{};
|
||||
for (final Target target in targets) {
|
||||
final BuildResult result = await buildRunner.build(
|
||||
linkModePreference: LinkModePreference.dynamic,
|
||||
target: target,
|
||||
targetIOSSdk: iosSdk,
|
||||
buildMode: buildModeCli,
|
||||
workingDirectory: projectUri,
|
||||
includeParentEnvironment: true,
|
||||
cCompilerConfig: await buildRunner.cCompilerConfig,
|
||||
);
|
||||
nativeAssets.addAll(result.assets);
|
||||
dependencies.addAll(result.dependencies);
|
||||
}
|
||||
ensureNoLinkModeStatic(nativeAssets);
|
||||
globals.logger.printTrace('Building native assets for $targets done.');
|
||||
final Map<AssetPath, List<Asset>> fatAssetTargetLocations = _fatAssetTargetLocations(nativeAssets);
|
||||
await copyNativeAssetsMacOSHost(
|
||||
buildUri_,
|
||||
fatAssetTargetLocations,
|
||||
codesignIdentity,
|
||||
buildMode,
|
||||
fileSystem,
|
||||
);
|
||||
|
||||
final Map<Asset, Asset> assetTargetLocations = _assetTargetLocations(nativeAssets);
|
||||
await writeNativeAssetsYaml(
|
||||
assetTargetLocations.values,
|
||||
yamlParentDirectory,
|
||||
fileSystem,
|
||||
);
|
||||
return dependencies.toList();
|
||||
}
|
||||
|
||||
IOSSdk _getIOSSdk(EnvironmentType environmentType) {
|
||||
switch (environmentType) {
|
||||
case EnvironmentType.physical:
|
||||
return IOSSdk.iPhoneOs;
|
||||
case EnvironmentType.simulator:
|
||||
return IOSSdk.iPhoneSimulator;
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the [Target] from a [DarwinArch].
|
||||
Target _getNativeTarget(DarwinArch darwinArch) {
|
||||
switch (darwinArch) {
|
||||
case DarwinArch.armv7:
|
||||
return Target.iOSArm;
|
||||
case DarwinArch.arm64:
|
||||
return Target.iOSArm64;
|
||||
case DarwinArch.x86_64:
|
||||
return Target.iOSX64;
|
||||
}
|
||||
}
|
||||
|
||||
Map<AssetPath, List<Asset>> _fatAssetTargetLocations(List<Asset> nativeAssets) {
|
||||
final Map<AssetPath, List<Asset>> result = <AssetPath, List<Asset>>{};
|
||||
for (final Asset asset in nativeAssets) {
|
||||
final AssetPath path = _targetLocationIOS(asset).path;
|
||||
result[path] ??= <Asset>[];
|
||||
result[path]!.add(asset);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Map<Asset, Asset> _assetTargetLocations(List<Asset> nativeAssets) => <Asset, Asset>{
|
||||
for (final Asset asset in nativeAssets)
|
||||
asset: _targetLocationIOS(asset),
|
||||
};
|
||||
|
||||
Asset _targetLocationIOS(Asset asset) {
|
||||
final AssetPath path = asset.path;
|
||||
switch (path) {
|
||||
case AssetSystemPath _:
|
||||
case AssetInExecutable _:
|
||||
case AssetInProcess _:
|
||||
return asset;
|
||||
case AssetAbsolutePath _:
|
||||
final String fileName = path.uri.pathSegments.last;
|
||||
return asset.copyWith(path: AssetAbsolutePath(Uri(path: fileName)));
|
||||
}
|
||||
throw Exception('Unsupported asset path type ${path.runtimeType} in asset $asset');
|
||||
}
|
||||
162
packages/flutter_tools/lib/src/macos/native_assets.dart
Normal file
162
packages/flutter_tools/lib/src/macos/native_assets.dart
Normal file
@@ -0,0 +1,162 @@
|
||||
// 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:native_assets_builder/native_assets_builder.dart' show BuildResult;
|
||||
import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode;
|
||||
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
|
||||
|
||||
import '../base/file_system.dart';
|
||||
import '../build_info.dart';
|
||||
import '../globals.dart' as globals;
|
||||
import '../native_assets.dart';
|
||||
import 'native_assets_host.dart';
|
||||
|
||||
/// Dry run the native builds.
|
||||
///
|
||||
/// This does not build native assets, it only simulates what the final paths
|
||||
/// of all assets will be so that this can be embedded in the kernel file and
|
||||
/// the Xcode project.
|
||||
Future<Uri?> dryRunNativeAssetsMacOS({
|
||||
required NativeAssetsBuildRunner buildRunner,
|
||||
required Uri projectUri,
|
||||
bool flutterTester = false,
|
||||
required FileSystem fileSystem,
|
||||
}) async {
|
||||
if (await hasNoPackageConfig(buildRunner) || await isDisabledAndNoNativeAssets(buildRunner)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Uri buildUri_ = nativeAssetsBuildUri(projectUri, OS.macOS);
|
||||
final Iterable<Asset> nativeAssetPaths = await dryRunNativeAssetsMacOSInternal(fileSystem, projectUri, flutterTester, buildRunner);
|
||||
final Uri nativeAssetsUri = await writeNativeAssetsYaml(nativeAssetPaths, buildUri_, fileSystem);
|
||||
return nativeAssetsUri;
|
||||
}
|
||||
|
||||
Future<Iterable<Asset>> dryRunNativeAssetsMacOSInternal(
|
||||
FileSystem fileSystem,
|
||||
Uri projectUri,
|
||||
bool flutterTester,
|
||||
NativeAssetsBuildRunner buildRunner,
|
||||
) async {
|
||||
const OS targetOs = OS.macOS;
|
||||
final Uri buildUri_ = nativeAssetsBuildUri(projectUri, targetOs);
|
||||
|
||||
globals.logger.printTrace('Dry running native assets for $targetOs.');
|
||||
final List<Asset> nativeAssets = (await buildRunner.dryRun(
|
||||
linkModePreference: LinkModePreference.dynamic,
|
||||
targetOs: targetOs,
|
||||
workingDirectory: projectUri,
|
||||
includeParentEnvironment: true,
|
||||
))
|
||||
.assets;
|
||||
ensureNoLinkModeStatic(nativeAssets);
|
||||
globals.logger.printTrace('Dry running native assets for $targetOs done.');
|
||||
final Uri? absolutePath = flutterTester ? buildUri_ : null;
|
||||
final Map<Asset, Asset> assetTargetLocations = _assetTargetLocations(nativeAssets, absolutePath);
|
||||
final Iterable<Asset> nativeAssetPaths = assetTargetLocations.values;
|
||||
return nativeAssetPaths;
|
||||
}
|
||||
|
||||
/// Builds native assets.
|
||||
///
|
||||
/// If [darwinArchs] is omitted, the current target architecture is used.
|
||||
///
|
||||
/// If [flutterTester] is true, absolute paths are emitted in the native
|
||||
/// assets mapping. This can be used for JIT mode without sandbox on the host.
|
||||
/// This is used in `flutter test` and `flutter run -d flutter-tester`.
|
||||
Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> buildNativeAssetsMacOS({
|
||||
required NativeAssetsBuildRunner buildRunner,
|
||||
List<DarwinArch>? darwinArchs,
|
||||
required Uri projectUri,
|
||||
required BuildMode buildMode,
|
||||
bool flutterTester = false,
|
||||
String? codesignIdentity,
|
||||
Uri? yamlParentDirectory,
|
||||
required FileSystem fileSystem,
|
||||
}) async {
|
||||
const OS targetOs = OS.macOS;
|
||||
final Uri buildUri_ = nativeAssetsBuildUri(projectUri, targetOs);
|
||||
if (await hasNoPackageConfig(buildRunner) || await isDisabledAndNoNativeAssets(buildRunner)) {
|
||||
final Uri nativeAssetsYaml = await writeNativeAssetsYaml(<Asset>[], yamlParentDirectory ?? buildUri_, fileSystem);
|
||||
return (nativeAssetsYaml, <Uri>[]);
|
||||
}
|
||||
|
||||
final List<Target> targets = darwinArchs != null ? darwinArchs.map(_getNativeTarget).toList() : <Target>[Target.current];
|
||||
final native_assets_cli.BuildMode buildModeCli = nativeAssetsBuildMode(buildMode);
|
||||
|
||||
globals.logger.printTrace('Building native assets for $targets $buildModeCli.');
|
||||
final List<Asset> nativeAssets = <Asset>[];
|
||||
final Set<Uri> dependencies = <Uri>{};
|
||||
for (final Target target in targets) {
|
||||
final BuildResult result = await buildRunner.build(
|
||||
linkModePreference: LinkModePreference.dynamic,
|
||||
target: target,
|
||||
buildMode: buildModeCli,
|
||||
workingDirectory: projectUri,
|
||||
includeParentEnvironment: true,
|
||||
cCompilerConfig: await buildRunner.cCompilerConfig,
|
||||
);
|
||||
nativeAssets.addAll(result.assets);
|
||||
dependencies.addAll(result.dependencies);
|
||||
}
|
||||
ensureNoLinkModeStatic(nativeAssets);
|
||||
globals.logger.printTrace('Building native assets for $targets done.');
|
||||
final Uri? absolutePath = flutterTester ? buildUri_ : null;
|
||||
final Map<Asset, Asset> assetTargetLocations = _assetTargetLocations(nativeAssets, absolutePath);
|
||||
final Map<AssetPath, List<Asset>> fatAssetTargetLocations = _fatAssetTargetLocations(nativeAssets, absolutePath);
|
||||
await copyNativeAssetsMacOSHost(buildUri_, fatAssetTargetLocations, codesignIdentity, buildMode, fileSystem);
|
||||
final Uri nativeAssetsUri = await writeNativeAssetsYaml(assetTargetLocations.values, yamlParentDirectory ?? buildUri_, fileSystem);
|
||||
return (nativeAssetsUri, dependencies.toList());
|
||||
}
|
||||
|
||||
/// Extract the [Target] from a [DarwinArch].
|
||||
Target _getNativeTarget(DarwinArch darwinArch) {
|
||||
switch (darwinArch) {
|
||||
case DarwinArch.arm64:
|
||||
return Target.macOSArm64;
|
||||
case DarwinArch.x86_64:
|
||||
return Target.macOSX64;
|
||||
case DarwinArch.armv7:
|
||||
throw Exception('Unknown DarwinArch: $darwinArch.');
|
||||
}
|
||||
}
|
||||
|
||||
Map<AssetPath, List<Asset>> _fatAssetTargetLocations(List<Asset> nativeAssets, Uri? absolutePath) {
|
||||
final Map<AssetPath, List<Asset>> result = <AssetPath, List<Asset>>{};
|
||||
for (final Asset asset in nativeAssets) {
|
||||
final AssetPath path = _targetLocationMacOS(asset, absolutePath).path;
|
||||
result[path] ??= <Asset>[];
|
||||
result[path]!.add(asset);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Map<Asset, Asset> _assetTargetLocations(List<Asset> nativeAssets, Uri? absolutePath) => <Asset, Asset>{
|
||||
for (final Asset asset in nativeAssets)
|
||||
asset: _targetLocationMacOS(asset, absolutePath),
|
||||
};
|
||||
|
||||
Asset _targetLocationMacOS(Asset asset, Uri? absolutePath) {
|
||||
final AssetPath path = asset.path;
|
||||
switch (path) {
|
||||
case AssetSystemPath _:
|
||||
case AssetInExecutable _:
|
||||
case AssetInProcess _:
|
||||
return asset;
|
||||
case AssetAbsolutePath _:
|
||||
final String fileName = path.uri.pathSegments.last;
|
||||
Uri uri;
|
||||
if (absolutePath != null) {
|
||||
// Flutter tester needs full host paths.
|
||||
uri = absolutePath.resolve(fileName);
|
||||
} else {
|
||||
// Flutter Desktop needs "absolute" paths inside the app.
|
||||
// "relative" in the context of native assets would be relative to the
|
||||
// kernel or aot snapshot.
|
||||
uri = Uri(path: fileName);
|
||||
}
|
||||
return asset.copyWith(path: AssetAbsolutePath(uri));
|
||||
}
|
||||
throw Exception('Unsupported asset path type ${path.runtimeType} in asset $asset');
|
||||
}
|
||||
141
packages/flutter_tools/lib/src/macos/native_assets_host.dart
Normal file
141
packages/flutter_tools/lib/src/macos/native_assets_host.dart
Normal file
@@ -0,0 +1,141 @@
|
||||
// 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.
|
||||
|
||||
// Shared logic between iOS and macOS implementations of native assets.
|
||||
|
||||
import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode;
|
||||
|
||||
import '../base/common.dart';
|
||||
import '../base/file_system.dart';
|
||||
import '../base/io.dart';
|
||||
import '../build_info.dart';
|
||||
import '../convert.dart';
|
||||
import '../globals.dart' as globals;
|
||||
|
||||
/// The target location for native assets on macOS.
|
||||
///
|
||||
/// Because we need to have a multi-architecture solution for
|
||||
/// `flutter run --release`, we use `lipo` to combine all target architectures
|
||||
/// into a single file.
|
||||
///
|
||||
/// We need to set the install name so that it matches what the place it will
|
||||
/// be bundled in the final app.
|
||||
///
|
||||
/// Code signing is also done here, so that we don't have to worry about it
|
||||
/// in xcode_backend.dart and macos_assemble.sh.
|
||||
Future<void> copyNativeAssetsMacOSHost(
|
||||
Uri buildUri,
|
||||
Map<AssetPath, List<Asset>> assetTargetLocations,
|
||||
String? codesignIdentity,
|
||||
BuildMode buildMode,
|
||||
FileSystem fileSystem,
|
||||
) async {
|
||||
if (assetTargetLocations.isNotEmpty) {
|
||||
globals.logger.printTrace('Copying native assets to ${buildUri.toFilePath()}.');
|
||||
final Directory buildDir = fileSystem.directory(buildUri.toFilePath());
|
||||
if (!buildDir.existsSync()) {
|
||||
buildDir.createSync(recursive: true);
|
||||
}
|
||||
for (final MapEntry<AssetPath, List<Asset>> assetMapping in assetTargetLocations.entries) {
|
||||
final Uri target = (assetMapping.key as AssetAbsolutePath).uri;
|
||||
final List<Uri> sources = <Uri>[for (final Asset source in assetMapping.value) (source.path as AssetAbsolutePath).uri];
|
||||
final Uri targetUri = buildUri.resolveUri(target);
|
||||
final String targetFullPath = targetUri.toFilePath();
|
||||
await lipoDylibs(targetFullPath, sources);
|
||||
await setInstallNameDylib(targetUri);
|
||||
await codesignDylib(codesignIdentity, buildMode, targetFullPath);
|
||||
}
|
||||
globals.logger.printTrace('Copying native assets done.');
|
||||
}
|
||||
}
|
||||
|
||||
/// Combines dylibs from [sources] into a fat binary at [targetFullPath].
|
||||
///
|
||||
/// The dylibs must have different architectures. E.g. a dylib targeting
|
||||
/// arm64 ios simulator cannot be combined with a dylib targeting arm64
|
||||
/// ios device or macos arm64.
|
||||
Future<void> lipoDylibs(String targetFullPath, List<Uri> sources) async {
|
||||
final ProcessResult lipoResult = await globals.processManager.run(
|
||||
<String>[
|
||||
'lipo',
|
||||
'-create',
|
||||
'-output',
|
||||
targetFullPath,
|
||||
for (final Uri source in sources) source.toFilePath(),
|
||||
],
|
||||
);
|
||||
if (lipoResult.exitCode != 0) {
|
||||
throwToolExit('Failed to create universal binary:\n${lipoResult.stderr}');
|
||||
}
|
||||
globals.logger.printTrace(lipoResult.stdout as String);
|
||||
globals.logger.printTrace(lipoResult.stderr as String);
|
||||
}
|
||||
|
||||
/// Sets the install name in a dylib with a Mach-O format.
|
||||
///
|
||||
/// On macOS and iOS, opening a dylib at runtime fails if the path inside the
|
||||
/// dylib itself does not correspond to the path that the file is at. Therefore,
|
||||
/// native assets copied into their final location also need their install name
|
||||
/// updated with the `install_name_tool`.
|
||||
Future<void> setInstallNameDylib(Uri targetUri) async {
|
||||
final String fileName = targetUri.pathSegments.last;
|
||||
final ProcessResult installNameResult = await globals.processManager.run(
|
||||
<String>[
|
||||
'install_name_tool',
|
||||
'-id',
|
||||
'@executable_path/Frameworks/$fileName',
|
||||
targetUri.toFilePath(),
|
||||
],
|
||||
);
|
||||
if (installNameResult.exitCode != 0) {
|
||||
throwToolExit('Failed to change the install name of $targetUri:\n${installNameResult.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> codesignDylib(
|
||||
String? codesignIdentity,
|
||||
BuildMode buildMode,
|
||||
String targetFullPath,
|
||||
) async {
|
||||
if (codesignIdentity == null || codesignIdentity.isEmpty) {
|
||||
codesignIdentity = '-';
|
||||
}
|
||||
final List<String> codesignCommand = <String>[
|
||||
'codesign',
|
||||
'--force',
|
||||
'--sign',
|
||||
codesignIdentity,
|
||||
if (buildMode != BuildMode.release) ...<String>[
|
||||
// Mimic Xcode's timestamp codesigning behavior on non-release binaries.
|
||||
'--timestamp=none',
|
||||
],
|
||||
targetFullPath,
|
||||
];
|
||||
globals.logger.printTrace(codesignCommand.join(' '));
|
||||
final ProcessResult codesignResult = await globals.processManager.run(codesignCommand);
|
||||
if (codesignResult.exitCode != 0) {
|
||||
throwToolExit('Failed to code sign binary:\n${codesignResult.stderr}');
|
||||
}
|
||||
globals.logger.printTrace(codesignResult.stdout as String);
|
||||
globals.logger.printTrace(codesignResult.stderr as String);
|
||||
}
|
||||
|
||||
/// Flutter expects `xcrun` to be on the path on macOS hosts.
|
||||
///
|
||||
/// Use the `clang`, `ar`, and `ld` that would be used if run with `xcrun`.
|
||||
Future<CCompilerConfig> cCompilerConfigMacOS() async {
|
||||
final ProcessResult xcrunResult = await globals.processManager.run(<String>['xcrun', 'clang', '--version']);
|
||||
if (xcrunResult.exitCode != 0) {
|
||||
throwToolExit('Failed to find clang with xcrun:\n${xcrunResult.stderr}');
|
||||
}
|
||||
final String installPath = LineSplitter.split(xcrunResult.stdout as String)
|
||||
.firstWhere((String s) => s.startsWith('InstalledDir: '))
|
||||
.split(' ')
|
||||
.last;
|
||||
return CCompilerConfig(
|
||||
cc: Uri.file('$installPath/clang'),
|
||||
ar: Uri.file('$installPath/ar'),
|
||||
ld: Uri.file('$installPath/ld'),
|
||||
);
|
||||
}
|
||||
378
packages/flutter_tools/lib/src/native_assets.dart
Normal file
378
packages/flutter_tools/lib/src/native_assets.dart
Normal file
@@ -0,0 +1,378 @@
|
||||
// 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.
|
||||
|
||||
// Logic for native assets shared between all host OSes.
|
||||
|
||||
import 'package:logging/logging.dart' as logging;
|
||||
import 'package:native_assets_builder/native_assets_builder.dart' as native_assets_builder;
|
||||
import 'package:native_assets_cli/native_assets_cli.dart';
|
||||
import 'package:package_config/package_config_types.dart';
|
||||
|
||||
import 'base/common.dart';
|
||||
import 'base/file_system.dart';
|
||||
import 'base/logger.dart';
|
||||
import 'base/platform.dart';
|
||||
import 'build_info.dart' as build_info;
|
||||
import 'cache.dart';
|
||||
import 'features.dart';
|
||||
import 'globals.dart' as globals;
|
||||
import 'ios/native_assets.dart';
|
||||
import 'macos/native_assets.dart';
|
||||
import 'macos/native_assets_host.dart';
|
||||
import 'resident_runner.dart';
|
||||
|
||||
/// Programmatic API to be used by Dart launchers to invoke native builds.
|
||||
///
|
||||
/// It enables mocking `package:native_assets_builder` package.
|
||||
/// It also enables mocking native toolchain discovery via [cCompilerConfig].
|
||||
abstract class NativeAssetsBuildRunner {
|
||||
/// Whether the project has a `.dart_tools/package_config.json`.
|
||||
///
|
||||
/// If there is no package config, [packagesWithNativeAssets], [build], and
|
||||
/// [dryRun] must not be invoked.
|
||||
Future<bool> hasPackageConfig();
|
||||
|
||||
/// All packages in the transitive dependencies that have a `build.dart`.
|
||||
Future<List<Package>> packagesWithNativeAssets();
|
||||
|
||||
/// Runs all [packagesWithNativeAssets] `build.dart` in dry run.
|
||||
Future<native_assets_builder.DryRunResult> dryRun({
|
||||
required bool includeParentEnvironment,
|
||||
required LinkModePreference linkModePreference,
|
||||
required OS targetOs,
|
||||
required Uri workingDirectory,
|
||||
});
|
||||
|
||||
/// Runs all [packagesWithNativeAssets] `build.dart`.
|
||||
Future<native_assets_builder.BuildResult> build({
|
||||
required bool includeParentEnvironment,
|
||||
required BuildMode buildMode,
|
||||
required LinkModePreference linkModePreference,
|
||||
required Target target,
|
||||
required Uri workingDirectory,
|
||||
CCompilerConfig? cCompilerConfig,
|
||||
int? targetAndroidNdkApi,
|
||||
IOSSdk? targetIOSSdk,
|
||||
});
|
||||
|
||||
/// The C compiler config to use for compilation.
|
||||
Future<CCompilerConfig> get cCompilerConfig;
|
||||
}
|
||||
|
||||
/// Uses `package:native_assets_builder` for its implementation.
|
||||
class NativeAssetsBuildRunnerImpl implements NativeAssetsBuildRunner {
|
||||
NativeAssetsBuildRunnerImpl(this.projectUri, this.fileSystem, this.logger);
|
||||
|
||||
final Uri projectUri;
|
||||
final FileSystem fileSystem;
|
||||
final Logger logger;
|
||||
|
||||
late final logging.Logger _logger = logging.Logger('')
|
||||
..onRecord.listen((logging.LogRecord record) {
|
||||
final int levelValue = record.level.value;
|
||||
final String message = record.message;
|
||||
if (levelValue >= logging.Level.SEVERE.value) {
|
||||
logger.printError(message);
|
||||
} else if (levelValue >= logging.Level.WARNING.value) {
|
||||
logger.printWarning(message);
|
||||
} else if (levelValue >= logging.Level.INFO.value) {
|
||||
logger.printTrace(message);
|
||||
} else {
|
||||
logger.printTrace(message);
|
||||
}
|
||||
});
|
||||
|
||||
late final Uri _dartExecutable = fileSystem.directory(Cache.flutterRoot).uri.resolve('bin/dart');
|
||||
|
||||
late final native_assets_builder.NativeAssetsBuildRunner _buildRunner = native_assets_builder.NativeAssetsBuildRunner(
|
||||
logger: _logger,
|
||||
dartExecutable: _dartExecutable,
|
||||
);
|
||||
|
||||
native_assets_builder.PackageLayout? _packageLayout;
|
||||
|
||||
@override
|
||||
Future<bool> hasPackageConfig() {
|
||||
final File packageConfigJson = fileSystem
|
||||
.directory(projectUri.toFilePath())
|
||||
.childDirectory('.dart_tool')
|
||||
.childFile('package_config.json');
|
||||
return packageConfigJson.exists();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<Package>> packagesWithNativeAssets() async {
|
||||
_packageLayout ??= await native_assets_builder.PackageLayout.fromRootPackageRoot(projectUri);
|
||||
return _packageLayout!.packagesWithNativeAssets;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<native_assets_builder.DryRunResult> dryRun({
|
||||
required bool includeParentEnvironment,
|
||||
required LinkModePreference linkModePreference,
|
||||
required OS targetOs,
|
||||
required Uri workingDirectory,
|
||||
}) {
|
||||
return _buildRunner.dryRun(
|
||||
includeParentEnvironment: includeParentEnvironment,
|
||||
linkModePreference: linkModePreference,
|
||||
targetOs: targetOs,
|
||||
workingDirectory: workingDirectory,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<native_assets_builder.BuildResult> build({
|
||||
required bool includeParentEnvironment,
|
||||
required BuildMode buildMode,
|
||||
required LinkModePreference linkModePreference,
|
||||
required Target target,
|
||||
required Uri workingDirectory,
|
||||
CCompilerConfig? cCompilerConfig,
|
||||
int? targetAndroidNdkApi,
|
||||
IOSSdk? targetIOSSdk,
|
||||
}) {
|
||||
return _buildRunner.build(
|
||||
buildMode: buildMode,
|
||||
cCompilerConfig: cCompilerConfig,
|
||||
includeParentEnvironment: includeParentEnvironment,
|
||||
linkModePreference: linkModePreference,
|
||||
target: target,
|
||||
targetAndroidNdkApi: targetAndroidNdkApi,
|
||||
targetIOSSdk: targetIOSSdk,
|
||||
workingDirectory: workingDirectory,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
late final Future<CCompilerConfig> cCompilerConfig = () {
|
||||
if (globals.platform.isMacOS || globals.platform.isIOS) {
|
||||
return cCompilerConfigMacOS();
|
||||
}
|
||||
throwToolExit(
|
||||
'Native assets feature not yet implemented for Linux, Windows and Android.',
|
||||
);
|
||||
}();
|
||||
}
|
||||
|
||||
/// Write [assets] to `native_assets.yaml` in [yamlParentDirectory].
|
||||
Future<Uri> writeNativeAssetsYaml(
|
||||
Iterable<Asset> assets,
|
||||
Uri yamlParentDirectory,
|
||||
FileSystem fileSystem,
|
||||
) async {
|
||||
globals.logger.printTrace('Writing native_assets.yaml.');
|
||||
final String nativeAssetsDartContents = assets.toNativeAssetsFile();
|
||||
final Directory parentDirectory = fileSystem.directory(yamlParentDirectory);
|
||||
if (!await parentDirectory.exists()) {
|
||||
await parentDirectory.create(recursive: true);
|
||||
}
|
||||
final File nativeAssetsFile = parentDirectory.childFile('native_assets.yaml');
|
||||
await nativeAssetsFile.writeAsString(nativeAssetsDartContents);
|
||||
globals.logger.printTrace('Writing ${nativeAssetsFile.path} done.');
|
||||
return nativeAssetsFile.uri;
|
||||
}
|
||||
|
||||
/// Select the native asset build mode for a given Flutter build mode.
|
||||
BuildMode nativeAssetsBuildMode(build_info.BuildMode buildMode) {
|
||||
switch (buildMode) {
|
||||
case build_info.BuildMode.debug:
|
||||
return BuildMode.debug;
|
||||
case build_info.BuildMode.jitRelease:
|
||||
case build_info.BuildMode.profile:
|
||||
case build_info.BuildMode.release:
|
||||
return BuildMode.release;
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether this project does not yet have a package config file.
|
||||
///
|
||||
/// A project has no package config when `pub get` has not yet been run.
|
||||
///
|
||||
/// Native asset builds cannot be run without a package config. If there is
|
||||
/// no package config, leave a logging trace about that.
|
||||
Future<bool> hasNoPackageConfig(NativeAssetsBuildRunner buildRunner) async {
|
||||
final bool packageConfigExists = await buildRunner.hasPackageConfig();
|
||||
if (!packageConfigExists) {
|
||||
globals.logger.printTrace('No package config found. Skipping native assets compilation.');
|
||||
}
|
||||
return !packageConfigExists;
|
||||
}
|
||||
|
||||
/// Checks that if native assets is disabled, none of the dependencies declare
|
||||
/// native assets.
|
||||
///
|
||||
/// If any of the dependencies have native assets, but native assets are
|
||||
/// disabled, exits the tool.
|
||||
Future<bool> isDisabledAndNoNativeAssets(NativeAssetsBuildRunner buildRunner) async {
|
||||
if (featureFlags.isNativeAssetsEnabled) {
|
||||
return false;
|
||||
}
|
||||
final List<Package> packagesWithNativeAssets = await buildRunner.packagesWithNativeAssets();
|
||||
if (packagesWithNativeAssets.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
final String packageNames = packagesWithNativeAssets.map((Package p) => p.name).join(' ');
|
||||
throwToolExit(
|
||||
'Package(s) $packageNames require the native assets feature to be enabled. '
|
||||
'Enable using `flutter config --enable-native-assets`.',
|
||||
);
|
||||
}
|
||||
|
||||
/// Ensures that either this project has no native assets, or that native assets
|
||||
/// are supported on that operating system.
|
||||
///
|
||||
/// Exits the tool if the above condition is not satisfied.
|
||||
Future<void> ensureNoNativeAssetsOrOsIsSupported(
|
||||
Uri workingDirectory,
|
||||
String os,
|
||||
FileSystem fileSystem,
|
||||
NativeAssetsBuildRunner buildRunner,
|
||||
) async {
|
||||
if (await hasNoPackageConfig(buildRunner)) {
|
||||
return;
|
||||
}
|
||||
final List<Package> packagesWithNativeAssets = await buildRunner.packagesWithNativeAssets();
|
||||
if (packagesWithNativeAssets.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final String packageNames = packagesWithNativeAssets.map((Package p) => p.name).join(' ');
|
||||
throwToolExit(
|
||||
'Package(s) $packageNames require the native assets feature. '
|
||||
'This feature has not yet been implemented for `$os`. '
|
||||
'For more info see https://github.com/flutter/flutter/issues/129757.',
|
||||
);
|
||||
}
|
||||
|
||||
/// Ensure all native assets have a linkmode declared to be dynamic loading.
|
||||
///
|
||||
/// In JIT, the link mode must always be dynamic linking.
|
||||
/// In AOT, the static linking has not yet been implemented in Dart:
|
||||
/// https://github.com/dart-lang/sdk/issues/49418.
|
||||
///
|
||||
/// Therefore, ensure all `build.dart` scripts return only dynamic libraries.
|
||||
void ensureNoLinkModeStatic(List<Asset> nativeAssets) {
|
||||
final Iterable<Asset> staticAssets = nativeAssets.whereLinkMode(LinkMode.static);
|
||||
if (staticAssets.isNotEmpty) {
|
||||
final String assetIds = staticAssets.map((Asset a) => a.id).toSet().join(', ');
|
||||
throwToolExit(
|
||||
'Native asset(s) $assetIds have their link mode set to static, '
|
||||
'but this is not yet supported. '
|
||||
'For more info see https://github.com/dart-lang/sdk/issues/49418.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// This should be the same for different archs, debug/release, etc.
|
||||
/// It should work for all macOS.
|
||||
Uri nativeAssetsBuildUri(Uri projectUri, OS os) {
|
||||
final String buildDir = build_info.getBuildDirectory();
|
||||
return projectUri.resolve('$buildDir/native_assets/$os/');
|
||||
}
|
||||
|
||||
/// Gets the native asset id to dylib mapping to embed in the kernel file.
|
||||
///
|
||||
/// Run hot compiles a kernel file that is pushed to the device after hot
|
||||
/// restart. We need to embed the native assets mapping in order to access
|
||||
/// native assets after hot restart.
|
||||
Future<Uri?> dryRunNativeAssets({
|
||||
required Uri projectUri,
|
||||
required FileSystem fileSystem,
|
||||
required NativeAssetsBuildRunner buildRunner,
|
||||
required List<FlutterDevice> flutterDevices,
|
||||
}) async {
|
||||
if (flutterDevices.length != 1) {
|
||||
return dryRunNativeAssetsMultipeOSes(
|
||||
projectUri: projectUri,
|
||||
fileSystem: fileSystem,
|
||||
targetPlatforms: flutterDevices.map((FlutterDevice d) => d.targetPlatform).nonNulls,
|
||||
buildRunner: buildRunner,
|
||||
);
|
||||
}
|
||||
final FlutterDevice flutterDevice = flutterDevices.single;
|
||||
final build_info.TargetPlatform targetPlatform = flutterDevice.targetPlatform!;
|
||||
|
||||
final Uri? nativeAssetsYaml;
|
||||
switch (targetPlatform) {
|
||||
case build_info.TargetPlatform.darwin:
|
||||
nativeAssetsYaml = await dryRunNativeAssetsMacOS(
|
||||
projectUri: projectUri,
|
||||
fileSystem: fileSystem,
|
||||
buildRunner: buildRunner,
|
||||
);
|
||||
case build_info.TargetPlatform.ios:
|
||||
nativeAssetsYaml = await dryRunNativeAssetsIOS(
|
||||
projectUri: projectUri,
|
||||
fileSystem: fileSystem,
|
||||
buildRunner: buildRunner,
|
||||
);
|
||||
case build_info.TargetPlatform.tester:
|
||||
if (const LocalPlatform().isMacOS) {
|
||||
nativeAssetsYaml = await dryRunNativeAssetsMacOS(
|
||||
projectUri: projectUri,
|
||||
flutterTester: true,
|
||||
fileSystem: fileSystem,
|
||||
buildRunner: buildRunner,
|
||||
);
|
||||
} else {
|
||||
await ensureNoNativeAssetsOrOsIsSupported(
|
||||
projectUri,
|
||||
const LocalPlatform().operatingSystem,
|
||||
fileSystem,
|
||||
buildRunner,
|
||||
);
|
||||
nativeAssetsYaml = null;
|
||||
}
|
||||
case build_info.TargetPlatform.android_arm:
|
||||
case build_info.TargetPlatform.android_arm64:
|
||||
case build_info.TargetPlatform.android_x64:
|
||||
case build_info.TargetPlatform.android_x86:
|
||||
case build_info.TargetPlatform.android:
|
||||
case build_info.TargetPlatform.fuchsia_arm64:
|
||||
case build_info.TargetPlatform.fuchsia_x64:
|
||||
case build_info.TargetPlatform.linux_arm64:
|
||||
case build_info.TargetPlatform.linux_x64:
|
||||
case build_info.TargetPlatform.web_javascript:
|
||||
case build_info.TargetPlatform.windows_x64:
|
||||
await ensureNoNativeAssetsOrOsIsSupported(
|
||||
projectUri,
|
||||
targetPlatform.toString(),
|
||||
fileSystem,
|
||||
buildRunner,
|
||||
);
|
||||
nativeAssetsYaml = null;
|
||||
}
|
||||
return nativeAssetsYaml;
|
||||
}
|
||||
|
||||
/// Dry run the native builds for multiple OSes.
|
||||
///
|
||||
/// Needed for `flutter run -d all`.
|
||||
Future<Uri?> dryRunNativeAssetsMultipeOSes({
|
||||
required NativeAssetsBuildRunner buildRunner,
|
||||
required Uri projectUri,
|
||||
required FileSystem fileSystem,
|
||||
required Iterable<build_info.TargetPlatform> targetPlatforms,
|
||||
}) async {
|
||||
if (await hasNoPackageConfig(buildRunner) || await isDisabledAndNoNativeAssets(buildRunner)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Uri buildUri_ = buildUriMultiple(projectUri);
|
||||
final Iterable<Asset> nativeAssetPaths = <Asset>[
|
||||
if (targetPlatforms.contains(build_info.TargetPlatform.darwin) ||
|
||||
(targetPlatforms.contains(build_info.TargetPlatform.tester) && OS.current == OS.macOS))
|
||||
...await dryRunNativeAssetsMacOSInternal(fileSystem, projectUri, false, buildRunner),
|
||||
if (targetPlatforms.contains(build_info.TargetPlatform.ios)) ...await dryRunNativeAssetsIOSInternal(fileSystem, projectUri, buildRunner)
|
||||
];
|
||||
final Uri nativeAssetsUri = await writeNativeAssetsYaml(nativeAssetPaths, buildUri_, fileSystem);
|
||||
return nativeAssetsUri;
|
||||
}
|
||||
|
||||
/// With `flutter run -d all` we need a place to store the native assets
|
||||
/// mapping for multiple OSes combined.
|
||||
Uri buildUriMultiple(Uri projectUri) {
|
||||
final String buildDir = build_info.getBuildDirectory();
|
||||
return projectUri.resolve('$buildDir/native_assets/multiple/');
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import 'dart/package_map.dart';
|
||||
import 'devfs.dart';
|
||||
import 'device.dart';
|
||||
import 'globals.dart' as globals;
|
||||
import 'native_assets.dart';
|
||||
import 'project.dart';
|
||||
import 'reporting/reporting.dart';
|
||||
import 'resident_runner.dart';
|
||||
@@ -92,9 +93,11 @@ class HotRunner extends ResidentRunner {
|
||||
StopwatchFactory stopwatchFactory = const StopwatchFactory(),
|
||||
ReloadSourcesHelper reloadSourcesHelper = defaultReloadSourcesHelper,
|
||||
ReassembleHelper reassembleHelper = _defaultReassembleHelper,
|
||||
NativeAssetsBuildRunner? buildRunner,
|
||||
}) : _stopwatchFactory = stopwatchFactory,
|
||||
_reloadSourcesHelper = reloadSourcesHelper,
|
||||
_reassembleHelper = reassembleHelper,
|
||||
_buildRunner = buildRunner,
|
||||
super(
|
||||
hotMode: true,
|
||||
);
|
||||
@@ -132,6 +135,8 @@ class HotRunner extends ResidentRunner {
|
||||
String? _sdkName;
|
||||
bool? _emulator;
|
||||
|
||||
NativeAssetsBuildRunner? _buildRunner;
|
||||
|
||||
Future<void> _calculateTargetPlatform() async {
|
||||
if (_targetPlatform != null) {
|
||||
return;
|
||||
@@ -360,6 +365,15 @@ class HotRunner extends ResidentRunner {
|
||||
}) async {
|
||||
await _calculateTargetPlatform();
|
||||
|
||||
final Uri projectUri = Uri.directory(projectRootPath);
|
||||
_buildRunner ??= NativeAssetsBuildRunnerImpl(projectUri, fileSystem, globals.logger);
|
||||
final Uri? nativeAssetsYaml = await dryRunNativeAssets(
|
||||
projectUri: projectUri,
|
||||
fileSystem: fileSystem,
|
||||
buildRunner: _buildRunner!,
|
||||
flutterDevices: flutterDevices,
|
||||
);
|
||||
|
||||
final Stopwatch appStartedTimer = Stopwatch()..start();
|
||||
final File mainFile = globals.fs.file(mainPath);
|
||||
firstBuildTime = DateTime.now();
|
||||
@@ -391,6 +405,7 @@ class HotRunner extends ResidentRunner {
|
||||
packageConfig: debuggingOptions.buildInfo.packageConfig,
|
||||
projectRootPath: FlutterProject.current().directory.absolute.path,
|
||||
fs: globals.fs,
|
||||
nativeAssetsYaml: nativeAssetsYaml,
|
||||
).then((CompilerOutput? output) {
|
||||
compileTimer.stop();
|
||||
totalCompileTime += compileTimer.elapsed;
|
||||
|
||||
@@ -10,11 +10,14 @@ import 'package:meta/meta.dart';
|
||||
|
||||
import '../artifacts.dart';
|
||||
import '../base/file_system.dart';
|
||||
import '../base/platform.dart';
|
||||
import '../build_info.dart';
|
||||
import '../bundle.dart';
|
||||
import '../compile.dart';
|
||||
import '../flutter_plugins.dart';
|
||||
import '../globals.dart' as globals;
|
||||
import '../macos/native_assets.dart';
|
||||
import '../native_assets.dart';
|
||||
import '../project.dart';
|
||||
import 'test_time_recorder.dart';
|
||||
|
||||
@@ -163,6 +166,26 @@ class TestCompiler {
|
||||
invalidatedRegistrantFiles.add(flutterProject!.dartPluginRegistrant.absolute.uri);
|
||||
}
|
||||
|
||||
Uri? nativeAssetsYaml;
|
||||
final Uri projectUri = FlutterProject.current().directory.uri;
|
||||
final NativeAssetsBuildRunner buildRunner = NativeAssetsBuildRunnerImpl(projectUri, globals.fs, globals.logger);
|
||||
if (globals.platform.isMacOS) {
|
||||
(nativeAssetsYaml, _) = await buildNativeAssetsMacOS(
|
||||
buildMode: BuildMode.debug,
|
||||
projectUri: projectUri,
|
||||
flutterTester: true,
|
||||
fileSystem: globals.fs,
|
||||
buildRunner: buildRunner,
|
||||
);
|
||||
} else {
|
||||
await ensureNoNativeAssetsOrOsIsSupported(
|
||||
projectUri,
|
||||
const LocalPlatform().operatingSystem,
|
||||
globals.fs,
|
||||
buildRunner,
|
||||
);
|
||||
}
|
||||
|
||||
final CompilerOutput? compilerOutput = await compiler!.recompile(
|
||||
request.mainUri,
|
||||
<Uri>[request.mainUri, ...invalidatedRegistrantFiles],
|
||||
@@ -171,6 +194,7 @@ class TestCompiler {
|
||||
projectRootPath: flutterProject?.directory.absolute.path,
|
||||
checkDartPluginRegistry: true,
|
||||
fs: globals.fs,
|
||||
nativeAssetsYaml: nativeAssetsYaml,
|
||||
);
|
||||
final String? outputPath = compilerOutput?.outputFilename;
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import '../artifacts.dart';
|
||||
import '../base/file_system.dart';
|
||||
import '../base/io.dart';
|
||||
import '../base/logger.dart';
|
||||
import '../base/os.dart';
|
||||
import '../build_info.dart';
|
||||
import '../bundle.dart';
|
||||
import '../bundle_builder.dart';
|
||||
@@ -50,13 +49,11 @@ class FlutterTesterDevice extends Device {
|
||||
required Logger logger,
|
||||
required FileSystem fileSystem,
|
||||
required Artifacts artifacts,
|
||||
required OperatingSystemUtils operatingSystemUtils,
|
||||
}) : _processManager = processManager,
|
||||
_flutterVersion = flutterVersion,
|
||||
_logger = logger,
|
||||
_fileSystem = fileSystem,
|
||||
_artifacts = artifacts,
|
||||
_operatingSystemUtils = operatingSystemUtils,
|
||||
_artifacts = artifacts,
|
||||
super(
|
||||
platformType: null,
|
||||
category: null,
|
||||
@@ -68,7 +65,6 @@ class FlutterTesterDevice extends Device {
|
||||
final Logger _logger;
|
||||
final FileSystem _fileSystem;
|
||||
final Artifacts _artifacts;
|
||||
final OperatingSystemUtils _operatingSystemUtils;
|
||||
|
||||
Process? _process;
|
||||
final DevicePortForwarder _portForwarder = const NoOpDevicePortForwarder();
|
||||
@@ -157,7 +153,7 @@ class FlutterTesterDevice extends Device {
|
||||
buildInfo: buildInfo,
|
||||
mainPath: mainPath,
|
||||
applicationKernelFilePath: applicationKernelFilePath,
|
||||
platform: getTargetPlatformForName(getNameForHostPlatform(_operatingSystemUtils.hostPlatform)),
|
||||
platform: TargetPlatform.tester,
|
||||
assetDirPath: assetDirectory.path,
|
||||
);
|
||||
|
||||
@@ -258,15 +254,13 @@ class FlutterTesterDevices extends PollingDeviceDiscovery {
|
||||
required ProcessManager processManager,
|
||||
required Logger logger,
|
||||
required FlutterVersion flutterVersion,
|
||||
required OperatingSystemUtils operatingSystemUtils,
|
||||
}) : _testerDevice = FlutterTesterDevice(
|
||||
kTesterDeviceId,
|
||||
fileSystem: fileSystem,
|
||||
artifacts: artifacts,
|
||||
processManager: processManager,
|
||||
logger: logger,
|
||||
flutterVersion: flutterVersion,
|
||||
operatingSystemUtils: operatingSystemUtils,
|
||||
flutterVersion: flutterVersion,
|
||||
),
|
||||
super('Flutter tester');
|
||||
|
||||
|
||||
Reference in New Issue
Block a user