FFI plugins (#96225)

This commit is contained in:
Daco Harkes
2022-01-26 23:44:45 +01:00
committed by GitHub
parent f15dd780d4
commit 0e2f51dfd0
59 changed files with 1441 additions and 254 deletions

View File

@@ -48,8 +48,12 @@ class CreateCommand extends CreateBase {
flutterProjectTypeToString(FlutterProjectType.package): 'Generate a shareable Flutter project containing modular '
'Dart code.',
flutterProjectTypeToString(FlutterProjectType.plugin): 'Generate a shareable Flutter project containing an API '
'in Dart code with a platform-specific implementation for Android, for iOS code, or '
'for both.',
'in Dart code with a platform-specific implementation through method channels for Android, iOS, '
'Linux, macOS, Windows, web, or any combination of these.',
flutterProjectTypeToString(FlutterProjectType.ffiPlugin):
'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.',
flutterProjectTypeToString(FlutterProjectType.module): 'Generate a project to add a Flutter module to an '
'existing Android or iOS application.',
},
@@ -159,18 +163,17 @@ class CreateCommand extends CreateBase {
final bool metadataExists = projectDir.absolute.childFile('.metadata').existsSync();
if (argResults['template'] != null) {
template = stringToProjectType(stringArg('template'));
} else {
// If the project directory exists and isn't empty, then try to determine the template
// type from the project directory.
if (projectDir.existsSync() && projectDir.listSync().isNotEmpty) {
detectedProjectType = determineTemplateType();
if (detectedProjectType == null && metadataExists) {
// We can only be definitive that this is the wrong type if the .metadata file
// exists and contains a type that we don't understand, or doesn't contain a type.
throwToolExit('Sorry, unable to detect the type of project to recreate. '
'Try creating a fresh project and migrating your existing code to '
'the new project manually.');
}
}
// If the project directory exists and isn't empty, then try to determine the template
// type from the project directory.
if (projectDir.existsSync() && projectDir.listSync().isNotEmpty) {
detectedProjectType = determineTemplateType();
if (detectedProjectType == null && metadataExists) {
// We can only be definitive that this is the wrong type if the .metadata file
// exists and contains a type that we don't understand, or doesn't contain a type.
throwToolExit('Sorry, unable to detect the type of project to recreate. '
'Try creating a fresh project and migrating your existing code to '
'the new project manually.');
}
}
template ??= detectedProjectType ?? FlutterProjectType.app;
@@ -206,7 +209,8 @@ class CreateCommand extends CreateBase {
final FlutterProjectType template = _getProjectType(projectDir);
final bool generateModule = template == FlutterProjectType.module;
final bool generatePlugin = template == FlutterProjectType.plugin;
final bool generateMethodChannelsPlugin = template == FlutterProjectType.plugin;
final bool generateFfiPlugin = template == FlutterProjectType.ffiPlugin;
final bool generatePackage = template == FlutterProjectType.package;
final List<String> platforms = stringsArg('platforms');
@@ -220,6 +224,23 @@ class CreateCommand extends CreateBase {
} else if (platforms == null || platforms.isEmpty) {
throwToolExit('Must specify at least one platform using --platforms',
exitCode: 2);
} else if (generateFfiPlugin && argResults.wasParsed('platforms') && platforms.contains('web')) {
throwToolExit(
'The web platform is not supported in plugin_ffi template.',
exitCode: 2,
);
} else if (generateFfiPlugin && argResults.wasParsed('ios-language')) {
throwToolExit(
'The "ios-language" option is not supported with the plugin_ffi '
'template: the language will always be C or C++.',
exitCode: 2,
);
} else if (generateFfiPlugin && argResults.wasParsed('android-language')) {
throwToolExit(
'The "android-language" option is not supported with the plugin_ffi '
'template: the language will always be C or C++.',
exitCode: 2,
);
}
final String organization = await getOrganization();
@@ -257,7 +278,8 @@ class CreateCommand extends CreateBase {
titleCaseProjectName: titleCaseProjectName,
projectDescription: stringArg('description'),
flutterRoot: flutterRoot,
withPluginHook: generatePlugin,
withPlatformChannelPluginHook: generateMethodChannelsPlugin,
withFfiPluginHook: generateFfiPlugin,
androidLanguage: stringArg('android-language'),
iosLanguage: stringArg('ios-language'),
iosDevelopmentTeam: developmentTeam,
@@ -293,7 +315,7 @@ class CreateCommand extends CreateBase {
switch (template) {
case FlutterProjectType.app:
generatedFileCount += await generateApp(
'app',
<String>['app', 'app_test_widget'],
relativeDir,
templateContext,
overwrite: overwrite,
@@ -302,7 +324,7 @@ class CreateCommand extends CreateBase {
break;
case FlutterProjectType.skeleton:
generatedFileCount += await generateApp(
'skeleton',
<String>['skeleton'],
relativeDir,
templateContext,
overwrite: overwrite,
@@ -326,7 +348,15 @@ class CreateCommand extends CreateBase {
);
break;
case FlutterProjectType.plugin:
generatedFileCount += await _generatePlugin(
generatedFileCount += await _generateMethodChannelPlugin(
relativeDir,
templateContext,
overwrite: overwrite,
printStatusWhenWriting: !creatingNewProject,
);
break;
case FlutterProjectType.ffiPlugin:
generatedFileCount += await _generateFfiPlugin(
relativeDir,
templateContext,
overwrite: overwrite,
@@ -354,7 +384,7 @@ class CreateCommand extends CreateBase {
'main.dart',
));
globals.printStatus('Your module code is in $relativeMainPath.');
} else if (generatePlugin) {
} else if (generateMethodChannelsPlugin) {
final String relativePluginPath = globals.fs.path.normalize(globals.fs.path.relative(projectDirPath));
final List<String> requestedPlatforms = _getUserRequestedPlatforms();
final String platformsString = requestedPlatforms.join(', ');
@@ -460,7 +490,7 @@ Your $application code is in $relativeAppMain.
return generatedCount;
}
Future<int> _generatePlugin(
Future<int> _generateMethodChannelPlugin(
Directory directory,
Map<String, dynamic> templateContext, {
bool overwrite = false,
@@ -487,8 +517,8 @@ Your $application code is in $relativeAppMain.
? stringArg('description')
: 'A new flutter plugin project.';
templateContext['description'] = description;
generatedCount += await renderTemplate(
'plugin',
generatedCount += await renderMerged(
<String>['plugin', 'plugin_shared'],
directory,
templateContext,
overwrite: overwrite,
@@ -525,7 +555,83 @@ Your $application code is in $relativeAppMain.
templateContext['androidPluginIdentifier'] = androidPluginIdentifier;
generatedCount += await generateApp(
'app',
<String>['app', 'app_test_widget'],
project.example.directory,
templateContext,
overwrite: overwrite,
pluginExampleApp: true,
printStatusWhenWriting: printStatusWhenWriting,
);
return generatedCount;
}
Future<int> _generateFfiPlugin(
Directory directory,
Map<String, dynamic> templateContext, {
bool overwrite = false,
bool printStatusWhenWriting = true,
}) async {
// Plugins only add a platform if it was requested explicitly by the user.
if (!argResults.wasParsed('platforms')) {
for (final String platform in kAllCreatePlatforms) {
templateContext[platform] = false;
}
}
final List<String> platformsToAdd =
_getSupportedPlatformsFromTemplateContext(templateContext);
final List<String> existingPlatforms =
_getSupportedPlatformsInPlugin(directory);
for (final String existingPlatform in existingPlatforms) {
// re-generate files for existing platforms
templateContext[existingPlatform] = true;
}
final bool willAddPlatforms = platformsToAdd.isNotEmpty;
templateContext['no_platforms'] = !willAddPlatforms;
int generatedCount = 0;
final String description = argResults.wasParsed('description')
? stringArg('description')
: 'A new Flutter FFI plugin project.';
templateContext['description'] = description;
generatedCount += await renderMerged(
<String>['plugin_ffi', 'plugin_shared'],
directory,
templateContext,
overwrite: overwrite,
printStatusWhenWriting: printStatusWhenWriting,
);
if (boolArg('pub')) {
await pub.get(
context: PubContext.createPlugin,
directory: directory.path,
offline: boolArg('offline'),
generateSyntheticPackage: false,
);
}
final FlutterProject project = FlutterProject.fromDirectory(directory);
final bool generateAndroid = templateContext['android'] == true;
if (generateAndroid) {
gradle.updateLocalProperties(project: project, requireAndroidSdk: false);
}
final String projectName = templateContext['projectName'] as String;
final String organization = templateContext['organization'] as String;
final String androidPluginIdentifier = templateContext['androidIdentifier'] as String;
final String exampleProjectName = '${projectName}_example';
templateContext['projectName'] = exampleProjectName;
templateContext['androidIdentifier'] = CreateBase.createAndroidIdentifier(organization, exampleProjectName);
templateContext['iosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
templateContext['macosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
templateContext['windowsIdentifier'] = CreateBase.createWindowsIdentifier(organization, exampleProjectName);
templateContext['description'] = 'Demonstrates how to use the $projectName plugin.';
templateContext['pluginProjectName'] = projectName;
templateContext['androidPluginIdentifier'] = androidPluginIdentifier;
generatedCount += await generateApp(
<String>['app'],
project.example.directory,
templateContext,
overwrite: overwrite,

View File

@@ -5,6 +5,7 @@
// @dart = 2.8
import 'package:meta/meta.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:uuid/uuid.dart';
import '../android/android.dart' as android_common;
@@ -110,7 +111,7 @@ abstract class CreateBase extends FlutterCommand {
abbr: 'i',
defaultsTo: 'swift',
allowed: <String>['objc', 'swift'],
help: 'The language to use for iOS-specific code, either ObjectiveC (legacy) or Swift (recommended).'
help: 'The language to use for iOS-specific code, either Objective-C (legacy) or Swift (recommended).'
);
argParser.addOption(
'android-language',
@@ -339,7 +340,8 @@ abstract class CreateBase extends FlutterCommand {
String agpVersion,
String kotlinVersion,
String gradleVersion,
bool withPluginHook = false,
bool withPlatformChannelPluginHook = false,
bool withFfiPluginHook = false,
bool ios = false,
bool android = false,
bool web = false,
@@ -366,6 +368,12 @@ abstract class CreateBase extends FlutterCommand {
// https://developer.gnome.org/gio/stable/GApplication.html#g-application-id-is-valid
final String linuxIdentifier = androidIdentifier;
// TODO(dacoharkes): Replace with hardcoded version in template when Flutter 2.11 is released.
final Version ffiPluginStableRelease = Version(2, 11, 0);
final String minFrameworkVersionFfiPlugin = Version.parse(globals.flutterVersion.frameworkVersion) < ffiPluginStableRelease
? globals.flutterVersion.frameworkVersion
: ffiPluginStableRelease.toString();
return <String, Object>{
'organization': organization,
'projectName': projectName,
@@ -384,13 +392,16 @@ abstract class CreateBase extends FlutterCommand {
'pluginClassCapitalSnakeCase': pluginClassCapitalSnakeCase,
'pluginDartClass': pluginDartClass,
'pluginProjectUUID': const Uuid().v4().toUpperCase(),
'withPluginHook': withPluginHook,
'withFfiPluginHook': withFfiPluginHook,
'withPlatformChannelPluginHook': withPlatformChannelPluginHook,
'withPluginHook': withFfiPluginHook || withPlatformChannelPluginHook,
'androidLanguage': androidLanguage,
'iosLanguage': iosLanguage,
'hasIosDevelopmentTeam': iosDevelopmentTeam != null && iosDevelopmentTeam.isNotEmpty,
'iosDevelopmentTeam': iosDevelopmentTeam ?? '',
'flutterRevision': globals.flutterVersion.frameworkRevision,
'flutterChannel': globals.flutterVersion.channel,
'minFrameworkVersionFfiPlugin': minFrameworkVersionFfiPlugin,
'ios': ios,
'android': android,
'web': web,
@@ -468,7 +479,7 @@ abstract class CreateBase extends FlutterCommand {
/// If `overwrite` is true, overwrites existing files, `overwrite` defaults to `false`.
@protected
Future<int> generateApp(
String templateName,
List<String> templateNames,
Directory directory,
Map<String, Object> templateContext, {
bool overwrite = false,
@@ -477,7 +488,7 @@ abstract class CreateBase extends FlutterCommand {
}) async {
int generatedCount = 0;
generatedCount += await renderMerged(
<String>[templateName, 'app_shared'],
<String>[...templateNames, 'app_shared'],
directory,
templateContext,
overwrite: overwrite,

View File

@@ -120,7 +120,7 @@ List<Map<String, Object>> _filterPluginsByPlatform(List<Plugin> plugins, String
_kFlutterPluginsNameKey: plugin.name,
_kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path),
if (platformPlugin is NativeOrDartPlugin)
_kFlutterPluginsHasNativeBuildKey: (platformPlugin as NativeOrDartPlugin).isNative(),
_kFlutterPluginsHasNativeBuildKey: (platformPlugin as NativeOrDartPlugin).hasMethodChannel() || (platformPlugin as NativeOrDartPlugin).hasFfi(),
_kFlutterPluginsDependenciesKey: <String>[...plugin.dependencies.where(pluginNames.contains)],
});
}
@@ -270,9 +270,9 @@ const String _androidPluginRegistryTemplateOldEmbedding = '''
package io.flutter.plugins;
import io.flutter.plugin.common.PluginRegistry;
{{#plugins}}
{{#methodChannelPlugins}}
import {{package}}.{{class}};
{{/plugins}}
{{/methodChannelPlugins}}
/**
* Generated file. Do not edit.
@@ -282,9 +282,9 @@ public final class GeneratedPluginRegistrant {
if (alreadyRegisteredWith(registry)) {
return;
}
{{#plugins}}
{{#methodChannelPlugins}}
{{class}}.registerWith(registry.registrarFor("{{package}}.{{class}}"));
{{/plugins}}
{{/methodChannelPlugins}}
}
private static boolean alreadyRegisteredWith(PluginRegistry registry) {
@@ -322,7 +322,7 @@ public final class GeneratedPluginRegistrant {
{{#needsShim}}
ShimPluginRegistry shimPluginRegistry = new ShimPluginRegistry(flutterEngine);
{{/needsShim}}
{{#plugins}}
{{#methodChannelPlugins}}
{{#supportsEmbeddingV2}}
try {
flutterEngine.getPlugins().add(new {{package}}.{{class}}());
@@ -339,7 +339,7 @@ public final class GeneratedPluginRegistrant {
}
{{/supportsEmbeddingV1}}
{{/supportsEmbeddingV2}}
{{/plugins}}
{{/methodChannelPlugins}}
}
}
''';
@@ -363,12 +363,11 @@ AndroidEmbeddingVersion _getAndroidEmbeddingVersion(FlutterProject project) {
}
Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
final List<Plugin> nativePlugins = _filterNativePlugins(plugins, AndroidPlugin.kConfigKey);
final List<Map<String, Object?>> androidPlugins =
_extractPlatformMaps(nativePlugins, AndroidPlugin.kConfigKey);
final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, AndroidPlugin.kConfigKey);
final List<Map<String, Object?>> androidPlugins = _extractPlatformMaps(methodChannelPlugins, AndroidPlugin.kConfigKey);
final Map<String, Object> templateContext = <String, Object>{
'plugins': androidPlugins,
'methodChannelPlugins': androidPlugins,
'androidX': isAppUsingAndroidX(project.android.hostAppGradleRoot),
};
final String javaSourcePath = globals.fs.path.join(
@@ -485,20 +484,20 @@ const String _objcPluginRegistryImplementationTemplate = '''
#import "GeneratedPluginRegistrant.h"
{{#plugins}}
{{#methodChannelPlugins}}
#if __has_include(<{{name}}/{{class}}.h>)
#import <{{name}}/{{class}}.h>
#else
@import {{name}};
#endif
{{/plugins}}
{{/methodChannelPlugins}}
@implementation GeneratedPluginRegistrant
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {
{{#plugins}}
{{#methodChannelPlugins}}
[{{prefix}}{{class}} registerWithRegistrar:[registry registrarForPlugin:@"{{prefix}}{{class}}"]];
{{/plugins}}
{{/methodChannelPlugins}}
}
@end
@@ -512,14 +511,14 @@ const String _swiftPluginRegistryTemplate = '''
import {{framework}}
import Foundation
{{#plugins}}
{{#methodChannelPlugins}}
import {{name}}
{{/plugins}}
{{/methodChannelPlugins}}
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
{{#plugins}}
{{#methodChannelPlugins}}
{{class}}.register(with: registry.registrar(forPlugin: "{{class}}"))
{{/plugins}}
{{/methodChannelPlugins}}
}
''';
@@ -545,9 +544,9 @@ Depends on all your plugins, and provides a function to register them.
s.static_framework = true
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.dependency '{{framework}}'
{{#plugins}}
{{#methodChannelPlugins}}
s.dependency '{{name}}'
{{/plugins}}
{{/methodChannelPlugins}}
end
''';
@@ -559,17 +558,17 @@ const String _dartPluginRegistryTemplate = '''
// ignore_for_file: directives_ordering
// ignore_for_file: lines_longer_than_80_chars
{{#plugins}}
{{#methodChannelPlugins}}
import 'package:{{name}}/{{file}}';
{{/plugins}}
{{/methodChannelPlugins}}
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
// ignore: public_member_api_docs
void registerPlugins(Registrar registrar) {
{{#plugins}}
{{#methodChannelPlugins}}
{{class}}.registerWith(registrar);
{{/plugins}}
{{/methodChannelPlugins}}
registrar.registerMessageHandler();
}
''';
@@ -601,15 +600,15 @@ const String _cppPluginRegistryImplementationTemplate = '''
#include "generated_plugin_registrant.h"
{{#plugins}}
{{#methodChannelPlugins}}
#include <{{name}}/{{filename}}.h>
{{/plugins}}
{{/methodChannelPlugins}}
void RegisterPlugins(flutter::PluginRegistry* registry) {
{{#plugins}}
{{#methodChannelPlugins}}
{{class}}RegisterWithRegistrar(
registry->GetRegistrarForPlugin("{{class}}"));
{{/plugins}}
{{/methodChannelPlugins}}
}
''';
@@ -640,16 +639,16 @@ const String _linuxPluginRegistryImplementationTemplate = '''
#include "generated_plugin_registrant.h"
{{#plugins}}
{{#methodChannelPlugins}}
#include <{{name}}/{{filename}}.h>
{{/plugins}}
{{/methodChannelPlugins}}
void fl_register_plugins(FlPluginRegistry* registry) {
{{#plugins}}
{{#methodChannelPlugins}}
g_autoptr(FlPluginRegistrar) {{name}}_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "{{class}}");
{{filename}}_register_with_registrar({{name}}_registrar);
{{/plugins}}
{{/methodChannelPlugins}}
}
''';
@@ -659,9 +658,15 @@ const String _pluginCmakefileTemplate = r'''
#
list(APPEND FLUTTER_PLUGIN_LIST
{{#plugins}}
{{#methodChannelPlugins}}
{{name}}
{{/plugins}}
{{/methodChannelPlugins}}
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
{{#ffiPlugins}}
{{name}}
{{/ffiPlugins}}
)
set(PLUGIN_BUNDLED_LIBRARIES)
@@ -672,6 +677,11 @@ foreach(plugin ${FLUTTER_PLUGIN_LIST})
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory({{pluginsDir}}/${ffi_plugin}/{{os}} plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
''';
const String _dartPluginRegisterWith = r'''
@@ -760,13 +770,13 @@ void main(List<String> args) {
''';
Future<void> _writeIOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
final List<Plugin> nativePlugins = _filterNativePlugins(plugins, IOSPlugin.kConfigKey);
final List<Map<String, Object?>> iosPlugins = _extractPlatformMaps(nativePlugins, IOSPlugin.kConfigKey);
final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, IOSPlugin.kConfigKey);
final List<Map<String, Object?>> iosPlugins = _extractPlatformMaps(methodChannelPlugins, IOSPlugin.kConfigKey);
final Map<String, Object> context = <String, Object>{
'os': 'ios',
'deploymentTarget': '9.0',
'framework': 'Flutter',
'plugins': iosPlugins,
'methodChannelPlugins': iosPlugins,
};
if (project.isModule) {
final Directory registryDirectory = project.ios.pluginRegistrantHost;
@@ -810,11 +820,14 @@ String _cmakeRelativePluginSymlinkDirectoryPath(CmakeBasedProject project) {
}
Future<void> _writeLinuxPluginFiles(FlutterProject project, List<Plugin> plugins) async {
final List<Plugin>nativePlugins = _filterNativePlugins(plugins, LinuxPlugin.kConfigKey);
final List<Map<String, Object?>> linuxPlugins = _extractPlatformMaps(nativePlugins, LinuxPlugin.kConfigKey);
final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, LinuxPlugin.kConfigKey);
final List<Map<String, Object?>> linuxMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, LinuxPlugin.kConfigKey);
final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, LinuxPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains);
final List<Map<String, Object?>> linuxFfiPlugins = _extractPlatformMaps(ffiPlugins, LinuxPlugin.kConfigKey);
final Map<String, Object> context = <String, Object>{
'os': 'linux',
'plugins': linuxPlugins,
'methodChannelPlugins': linuxMethodChannelPlugins,
'ffiPlugins': linuxFfiPlugins,
'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.linux),
};
await _writeLinuxPluginRegistrant(project.linux.managedDirectory, context);
@@ -846,12 +859,12 @@ Future<void> _writePluginCmakefile(File destinationFile, Map<String, Object> tem
}
Future<void> _writeMacOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
final List<Plugin>nativePlugins = _filterNativePlugins(plugins, MacOSPlugin.kConfigKey);
final List<Map<String, Object?>> macosPlugins = _extractPlatformMaps(nativePlugins, MacOSPlugin.kConfigKey);
final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, MacOSPlugin.kConfigKey);
final List<Map<String, Object?>> macosMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, MacOSPlugin.kConfigKey);
final Map<String, Object> context = <String, Object>{
'os': 'macos',
'framework': 'FlutterMacOS',
'plugins': macosPlugins,
'methodChannelPlugins': macosMethodChannelPlugins,
};
_renderTemplateToFile(
_swiftPluginRegistryTemplate,
@@ -861,15 +874,15 @@ Future<void> _writeMacOSPluginRegistrant(FlutterProject project, List<Plugin> pl
);
}
/// Filters out Dart-only plugins, which shouldn't be added to the native generated registrants.
List<Plugin> _filterNativePlugins(List<Plugin> plugins, String platformKey) {
/// Filters out any plugins that don't use method channels, and thus shouldn't be added to the native generated registrants.
List<Plugin> _filterMethodChannelPlugins(List<Plugin> plugins, String platformKey) {
return plugins.where((Plugin element) {
final PluginPlatform? plugin = element.platforms[platformKey];
if (plugin == null) {
return false;
}
if (plugin is NativeOrDartPlugin) {
return (plugin as NativeOrDartPlugin).isNative();
return (plugin as NativeOrDartPlugin).hasMethodChannel();
}
// Not all platforms have the ability to create Dart-only plugins. Therefore, any plugin that doesn't
// implement NativeOrDartPlugin is always native.
@@ -877,6 +890,23 @@ List<Plugin> _filterNativePlugins(List<Plugin> plugins, String platformKey) {
}).toList();
}
/// Filters out Dart-only and method channel plugins.
///
/// FFI plugins do not need native code registration, but their binaries need to be bundled.
List<Plugin> _filterFfiPlugins(List<Plugin> plugins, String platformKey) {
return plugins.where((Plugin element) {
final PluginPlatform? plugin = element.platforms[platformKey];
if (plugin == null) {
return false;
}
if (plugin is NativeOrDartPlugin) {
final NativeOrDartPlugin plugin_ = plugin as NativeOrDartPlugin;
return plugin_.hasFfi();
}
return false;
}).toList();
}
/// Returns only the plugins with the given platform variant.
List<Plugin> _filterPluginsByVariant(List<Plugin> plugins, String platformKey, PluginPlatformVariant variant) {
return plugins.where((Plugin element) {
@@ -892,12 +922,15 @@ List<Plugin> _filterPluginsByVariant(List<Plugin> plugins, String platformKey, P
@visibleForTesting
Future<void> writeWindowsPluginFiles(FlutterProject project, List<Plugin> plugins, TemplateRenderer templateRenderer) async {
final List<Plugin> nativePlugins = _filterNativePlugins(plugins, WindowsPlugin.kConfigKey);
final List<Plugin> win32Plugins = _filterPluginsByVariant(nativePlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.win32);
final List<Map<String, Object?>> pluginInfo = _extractPlatformMaps(win32Plugins, WindowsPlugin.kConfigKey);
final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, WindowsPlugin.kConfigKey);
final List<Plugin> win32Plugins = _filterPluginsByVariant(methodChannelPlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.win32);
final List<Map<String, Object?>> windowsMethodChannelPlugins = _extractPlatformMaps(win32Plugins, WindowsPlugin.kConfigKey);
final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, WindowsPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains);
final List<Map<String, Object?>> windowsFfiPlugins = _extractPlatformMaps(ffiPlugins, WindowsPlugin.kConfigKey);
final Map<String, Object> context = <String, Object>{
'os': 'windows',
'plugins': pluginInfo,
'methodChannelPlugins': windowsMethodChannelPlugins,
'ffiPlugins': windowsFfiPlugins,
'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windows),
};
await _writeCppPluginRegistrant(project.windows.managedDirectory, context, templateRenderer);
@@ -908,12 +941,15 @@ Future<void> writeWindowsPluginFiles(FlutterProject project, List<Plugin> plugin
/// filtering, for the purposes of tooling support and initial UWP bootstrap.
@visibleForTesting
Future<void> writeWindowsUwpPluginFiles(FlutterProject project, List<Plugin> plugins, TemplateRenderer templateRenderer) async {
final List<Plugin> nativePlugins = _filterNativePlugins(plugins, WindowsPlugin.kConfigKey);
final List<Plugin> uwpPlugins = _filterPluginsByVariant(nativePlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.winuwp);
final List<Map<String, Object?>> pluginInfo = _extractPlatformMaps(uwpPlugins, WindowsPlugin.kConfigKey);
final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, WindowsPlugin.kConfigKey);
final List<Plugin> uwpPlugins = _filterPluginsByVariant(methodChannelPlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.winuwp);
final List<Map<String, Object?>> windowsMethodChannelPlugins = _extractPlatformMaps(uwpPlugins, WindowsPlugin.kConfigKey);
final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, WindowsPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains);
final List<Map<String, Object?>> windowsFfiPlugins = _extractPlatformMaps(ffiPlugins, WindowsPlugin.kConfigKey);
final Map<String, Object> context = <String, Object>{
'os': 'windows',
'plugins': pluginInfo,
'methodChannelPlugins': windowsMethodChannelPlugins,
'ffiPlugins': windowsFfiPlugins,
'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windowsUwp),
};
await _writeCppPluginRegistrant(project.windowsUwp.managedDirectory, context, templateRenderer);
@@ -938,7 +974,7 @@ Future<void> _writeCppPluginRegistrant(Directory destination, Map<String, Object
Future<void> _writeWebPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
final List<Map<String, Object?>> webPlugins = _extractPlatformMaps(plugins, WebPlugin.kConfigKey);
final Map<String, Object> context = <String, Object>{
'plugins': webPlugins,
'methodChannelPlugins': webPlugins,
};
final File pluginFile = project.web.libDirectory.childFile('generated_plugin_registrant.dart');
if (webPlugins.isEmpty) {

View File

@@ -23,9 +23,14 @@ enum FlutterProjectType {
package,
/// This is a native plugin project.
plugin,
/// This is an FFI native plugin project.
ffiPlugin,
}
String flutterProjectTypeToString(FlutterProjectType type) {
if (type == FlutterProjectType.ffiPlugin) {
return 'plugin_ffi';
}
return getEnumName(type);
}

View File

@@ -10,9 +10,12 @@ import 'base/file_system.dart';
/// Constant for 'pluginClass' key in plugin maps.
const String kPluginClass = 'pluginClass';
/// Constant for 'pluginClass' key in plugin maps.
/// Constant for 'dartPluginClass' key in plugin maps.
const String kDartPluginClass = 'dartPluginClass';
/// Constant for 'ffiPlugin' key in plugin maps.
const String kFfiPlugin = 'ffiPlugin';
// Constant for 'defaultPackage' key in plugin maps.
const String kDefaultPackage = 'default_package';
@@ -42,9 +45,14 @@ abstract class VariantPlatformPlugin {
}
abstract class NativeOrDartPlugin {
/// Determines whether the plugin has a native implementation or if it's a
/// Dart-only plugin.
bool isNative();
/// Determines whether the plugin has a Dart implementation.
bool hasDart();
/// Determines whether the plugin has a FFI implementation.
bool hasFfi();
/// Determines whether the plugin has a method channel implementation.
bool hasMethodChannel();
}
/// Contains parameters to template an Android plugin.
@@ -64,9 +72,11 @@ class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin {
this.package,
this.pluginClass,
this.dartPluginClass,
bool? ffiPlugin,
this.defaultPackage,
required FileSystem fileSystem,
}) : _fileSystem = fileSystem;
}) : _fileSystem = fileSystem,
ffiPlugin = ffiPlugin ?? false;
factory AndroidPlugin.fromYaml(String name, YamlMap yaml, String pluginPath, FileSystem fileSystem) {
assert(validate(yaml));
@@ -75,6 +85,7 @@ class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin {
package: yaml['package'] as String?,
pluginClass: yaml[kPluginClass] as String?,
dartPluginClass: yaml[kDartPluginClass] as String?,
ffiPlugin: yaml[kFfiPlugin] as bool?,
defaultPackage: yaml[kDefaultPackage] as String?,
pluginPath: pluginPath,
fileSystem: fileSystem,
@@ -84,15 +95,22 @@ class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin {
final FileSystem _fileSystem;
@override
bool isNative() => pluginClass != null;
bool hasMethodChannel() => pluginClass != null;
@override
bool hasFfi() => ffiPlugin;
@override
bool hasDart() => dartPluginClass != null;
static bool validate(YamlMap yaml) {
if (yaml == null) {
return false;
}
return (yaml['package'] is String && yaml['pluginClass'] is String)||
yaml[kDartPluginClass] is String ||
yaml[kDefaultPackage] is String;
return (yaml['package'] is String && yaml[kPluginClass] is String) ||
yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true ||
yaml[kDefaultPackage] is String;
}
static const String kConfigKey = 'android';
@@ -109,6 +127,9 @@ class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin {
/// The Dart plugin main class defined in pubspec.yaml, if any.
final String? dartPluginClass;
/// Is FFI plugin defined in pubspec.yaml.
final bool ffiPlugin;
/// The default implementation package defined in pubspec.yaml, if any.
final String? defaultPackage;
@@ -122,6 +143,7 @@ class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin {
if (package != null) 'package': package,
if (pluginClass != null) 'class': pluginClass,
if (dartPluginClass != null) kDartPluginClass : dartPluginClass,
if (ffiPlugin) kFfiPlugin: true,
if (defaultPackage != null) kDefaultPackage : defaultPackage,
// Mustache doesn't support complex types.
'supportsEmbeddingV1': _supportedEmbeddings.contains('1'),
@@ -214,8 +236,9 @@ class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
required this.classPrefix,
this.pluginClass,
this.dartPluginClass,
bool? ffiPlugin,
this.defaultPackage,
});
}) : ffiPlugin = ffiPlugin ?? false;
factory IOSPlugin.fromYaml(String name, YamlMap yaml) {
assert(validate(yaml)); // TODO(zanderso): https://github.com/flutter/flutter/issues/67241
@@ -224,6 +247,7 @@ class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
classPrefix: '',
pluginClass: yaml[kPluginClass] as String?,
dartPluginClass: yaml[kDartPluginClass] as String?,
ffiPlugin: yaml[kFfiPlugin] as bool?,
defaultPackage: yaml[kDefaultPackage] as String?,
);
}
@@ -233,8 +257,9 @@ class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
return false;
}
return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String ||
yaml[kDefaultPackage] is String;
yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true ||
yaml[kDefaultPackage] is String;
}
static const String kConfigKey = 'ios';
@@ -246,10 +271,17 @@ class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
final String classPrefix;
final String? pluginClass;
final String? dartPluginClass;
final bool ffiPlugin;
final String? defaultPackage;
@override
bool isNative() => pluginClass != null;
bool hasMethodChannel() => pluginClass != null;
@override
bool hasFfi() => ffiPlugin;
@override
bool hasDart() => dartPluginClass != null;
@override
Map<String, dynamic> toMap() {
@@ -258,6 +290,7 @@ class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
'prefix': classPrefix,
if (pluginClass != null) 'class': pluginClass,
if (dartPluginClass != null) kDartPluginClass : dartPluginClass,
if (ffiPlugin) kFfiPlugin: true,
if (defaultPackage != null) kDefaultPackage : defaultPackage,
};
}
@@ -265,15 +298,17 @@ class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
/// Contains the parameters to template a macOS plugin.
///
/// The [name] of the plugin is required. Either [dartPluginClass] or [pluginClass] are required.
/// The [name] of the plugin is required. Either [dartPluginClass] or
/// [pluginClass] or [ffiPlugin] are required.
/// [pluginClass] will be the entry point to the plugin's native code.
class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
const MacOSPlugin({
required this.name,
this.pluginClass,
this.dartPluginClass,
bool? ffiPlugin,
this.defaultPackage,
});
}) : ffiPlugin = ffiPlugin ?? false;
factory MacOSPlugin.fromYaml(String name, YamlMap yaml) {
assert(validate(yaml));
@@ -286,6 +321,7 @@ class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
name: name,
pluginClass: pluginClass,
dartPluginClass: yaml[kDartPluginClass] as String?,
ffiPlugin: yaml[kFfiPlugin] as bool?,
defaultPackage: yaml[kDefaultPackage] as String?,
);
}
@@ -295,8 +331,9 @@ class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
return false;
}
return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String ||
yaml[kDefaultPackage] is String;
yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true ||
yaml[kDefaultPackage] is String;
}
static const String kConfigKey = 'macos';
@@ -304,18 +341,26 @@ class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
final String name;
final String? pluginClass;
final String? dartPluginClass;
final bool ffiPlugin;
final String? defaultPackage;
@override
bool isNative() => pluginClass != null;
bool hasMethodChannel() => pluginClass != null;
@override
bool hasFfi() => ffiPlugin;
@override
bool hasDart() => dartPluginClass != null;
@override
Map<String, dynamic> toMap() {
return <String, dynamic>{
'name': name,
if (pluginClass != null) 'class': pluginClass,
if (dartPluginClass != null) kDartPluginClass : dartPluginClass,
if (defaultPackage != null) kDefaultPackage : defaultPackage,
if (dartPluginClass != null) kDartPluginClass: dartPluginClass,
if (ffiPlugin) kFfiPlugin: true,
if (defaultPackage != null) kDefaultPackage: defaultPackage,
};
}
}
@@ -324,14 +369,17 @@ class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin {
///
/// The [name] of the plugin is required. Either [dartPluginClass] or [pluginClass] are required.
/// [pluginClass] will be the entry point to the plugin's native code.
class WindowsPlugin extends PluginPlatform implements NativeOrDartPlugin, VariantPlatformPlugin {
class WindowsPlugin extends PluginPlatform
implements NativeOrDartPlugin, VariantPlatformPlugin {
const WindowsPlugin({
required this.name,
this.pluginClass,
this.dartPluginClass,
bool? ffiPlugin,
this.defaultPackage,
this.variants = const <PluginPlatformVariant>{},
}) : assert(pluginClass != null || dartPluginClass != null || defaultPackage != null);
}) : ffiPlugin = ffiPlugin ?? false,
assert(pluginClass != null || dartPluginClass != null || defaultPackage != null);
factory WindowsPlugin.fromYaml(String name, YamlMap yaml) {
assert(validate(yaml));
@@ -363,6 +411,7 @@ class WindowsPlugin extends PluginPlatform implements NativeOrDartPlugin, Varian
name: name,
pluginClass: pluginClass,
dartPluginClass: yaml[kDartPluginClass] as String?,
ffiPlugin: yaml[kFfiPlugin] as bool?,
defaultPackage: yaml[kDefaultPackage] as String?,
variants: variants,
);
@@ -374,8 +423,9 @@ class WindowsPlugin extends PluginPlatform implements NativeOrDartPlugin, Varian
}
return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String ||
yaml[kDefaultPackage] is String;
yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true ||
yaml[kDefaultPackage] is String;
}
static const String kConfigKey = 'windows';
@@ -383,6 +433,7 @@ class WindowsPlugin extends PluginPlatform implements NativeOrDartPlugin, Varian
final String name;
final String? pluginClass;
final String? dartPluginClass;
final bool ffiPlugin;
final String? defaultPackage;
final Set<PluginPlatformVariant> variants;
@@ -390,7 +441,13 @@ class WindowsPlugin extends PluginPlatform implements NativeOrDartPlugin, Varian
Set<PluginPlatformVariant> get supportedVariants => variants;
@override
bool isNative() => pluginClass != null;
bool hasMethodChannel() => pluginClass != null;
@override
bool hasFfi() => ffiPlugin;
@override
bool hasDart() => dartPluginClass != null;
@override
Map<String, dynamic> toMap() {
@@ -399,6 +456,7 @@ class WindowsPlugin extends PluginPlatform implements NativeOrDartPlugin, Varian
if (pluginClass != null) 'class': pluginClass!,
if (pluginClass != null) 'filename': _filenameForCppClass(pluginClass!),
if (dartPluginClass != null) kDartPluginClass: dartPluginClass!,
if (ffiPlugin) kFfiPlugin: true,
if (defaultPackage != null) kDefaultPackage: defaultPackage!,
};
}
@@ -413,8 +471,10 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin {
required this.name,
this.pluginClass,
this.dartPluginClass,
bool? ffiPlugin,
this.defaultPackage,
}) : assert(pluginClass != null || dartPluginClass != null || defaultPackage != null);
}) : ffiPlugin = ffiPlugin ?? false,
assert(pluginClass != null || dartPluginClass != null || ffiPlugin == true || defaultPackage != null);
factory LinuxPlugin.fromYaml(String name, YamlMap yaml) {
assert(validate(yaml));
@@ -427,6 +487,7 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin {
name: name,
pluginClass: pluginClass,
dartPluginClass: yaml[kDartPluginClass] as String?,
ffiPlugin: yaml[kFfiPlugin] as bool?,
defaultPackage: yaml[kDefaultPackage] as String?,
);
}
@@ -436,8 +497,9 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin {
return false;
}
return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String ||
yaml[kDefaultPackage] is String;
yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true ||
yaml[kDefaultPackage] is String;
}
static const String kConfigKey = 'linux';
@@ -445,10 +507,17 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin {
final String name;
final String? pluginClass;
final String? dartPluginClass;
final bool ffiPlugin;
final String? defaultPackage;
@override
bool isNative() => pluginClass != null;
bool hasMethodChannel() => pluginClass != null;
@override
bool hasFfi() => ffiPlugin;
@override
bool hasDart() => dartPluginClass != null;
@override
Map<String, dynamic> toMap() {
@@ -457,6 +526,7 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin {
if (pluginClass != null) 'class': pluginClass!,
if (pluginClass != null) 'filename': _filenameForCppClass(pluginClass!),
if (dartPluginClass != null) kDartPluginClass: dartPluginClass!,
if (ffiPlugin) kFfiPlugin: true,
if (defaultPackage != null) kDefaultPackage: defaultPackage!,
};
}

View File

@@ -49,12 +49,17 @@ class Plugin {
/// package: io.flutter.plugins.sample
/// pluginClass: SamplePlugin
/// ios:
/// # A plugin implemented through method channels.
/// pluginClass: SamplePlugin
/// linux:
/// pluginClass: SamplePlugin
/// # A plugin implemented purely in Dart code.
/// dartPluginClass: SamplePlugin
/// macos:
/// pluginClass: SamplePlugin
/// # A plugin implemented with `dart:ffi`.
/// ffiPlugin: true
/// windows:
/// # A plugin using platform-specific Dart and method channels.
/// dartPluginClass: SamplePlugin
/// pluginClass: SamplePlugin
factory Plugin.fromYaml(
String name,